首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Spring安全登录

Spring Spring安全登录
EN

Stack Overflow用户
提问于 2016-03-01 06:31:18
回答 2查看 352关注 0票数 1

我试图通过登录使用spring安全性。

代码语言:javascript
复制
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

    <form:form action="j_spring_security_check" method="POST" modelAttribute="loginForm">
        <table>
            <tr>
                <td colspan="2" align="center">Already have an account - Login</td>
            </tr>
            <tr>
                <td>Email</td>
                <td><form:input path="emailID" /> <form:errors path="emailID" class="error" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><form:password path="password" /> <form:errors path="password" class="error" /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="Login" /></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                    <a href="${pageontext.request.contextPath }/forgotpassword">Forgot Password</a>
                </td>
            </tr>                                   
        </table>                                        
    </form:form>
    <span class="error">${loginMessage}</span>

spring-security.xml

代码语言:javascript
复制
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/admin**" access="hasRole('ROLE_admin')" />

        <!-- access denied page -->
        <access-denied-handler error-page="/403" />
        <form-login 
            login-page="/login" 
            default-target-url="/index"
            authentication-failure-url="/login?error" 
            username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <csrf />
    </http>

    <beans:bean id="userAuthenticationProviderImpl" class="com.pir.authentication.UserAuthenticationProviderImpl" />

    <authentication-manager>
        <authentication-provider user-service-ref="userAuthenticationProviderImpl" >
            <password-encoder hash="plaintext" />    
        </authentication-provider>
    </authentication-manager>

</beans:beans>

UserAuthenticationProviderImpl.java

代码语言:javascript
复制
@Component(value = "authenticationProvider")
public class UserAuthenticationProviderImpl implements
        UserAuthenticationProvider {

    UserFunctionsService userFunctionsService;

    @Autowired(required=true)
    @Qualifier(value="userFunctionsService")
    public void setUserFunctionsService(UserFunctionsService userFunctionsService)
    {
        this.userFunctionsService = userFunctionsService;
    }

    /* (non-Javadoc)
     * @see com.pir.authentication.UserAuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) {
        // TODO Auto-generated method stub

        Users users = (Users) this.userFunctionsService.getUserDetails(authentication.getPrincipal().toString());

        if(users == null)
            throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal()));

        String suppliedPasswordHash = authentication.getCredentials().toString();

        if(users.getPassword().equals(suppliedPasswordHash)){
            throw new BadCredentialsException("Invalid credentials");
        }
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(users, null);

        return token;
    }

}

Users.java

代码语言:javascript
复制
@Entity
@Table(name = "users")
public class Users {

    @NotNull
    @Id
    @Column(name = "userID")
    private int userID;

    @NotNull
    @Size(min=3, max=50)
    @Pattern(regexp = ".+@.+\\.[a-z]+")
    @Column(name = "emailID")
    private String emailID;

    @NotNull
    @Size(min=3, max=50)
    @Column(name = "firstName")
    private String firstName;

    @NotNull
    @Size(min=3, max=50)
    @Column(name = "lastName")
    private String lastName;

    @NotNull
    @Size(min=3, max=50)
    @Column(name = "password")
    private String password;

    @NotNull
    @Column(name = "mobileNo")
    private String mobileNo;


    @Column(name = "imageURL")
    private String imageURL;

    @NotNull
    @DateTimeFormat(pattern="MM/dd/yyyy")
    @Column(name = "dateOfBirth")
    private String dateOfBirth;

    @NotNull
    @Column(name = "gender")
    private String gender;

    @NotNull
    @Column(name = "userType")
    private String userType;

    @Lob
    private MultipartFile image;

        //getters and setters
}

pir-servlet.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"
    xmlns:mvc="http://www.springframework.org/schema/mvc">

    <context:annotation-config />

    <context:component-scan base-package="com.pir" />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <bean id="myTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="userFunctionsDAO" class="com.pir.dao.UserFunctionsDAOImpl" />
    <bean id="userFunctionsService" class="com.pir.service.UserFunctionsServiceImpl" />

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576" />
    </bean>

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="com.mysql.jdbc.Driver"
    p:url="jdbc:mysql://localhost:3306/pir"
    p:username="root"
    p:password="user" />

    <bean id="tilesViewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles3.TilesView
            </value>
        </property> 
    </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
    </bean>

</beans>

当我尝试登录时,我希望登录成功或失败,但这会导致HTTP Status 404 -错误。这是我第一次尝试实现spring安全,所以对它没有太多的了解。我在这段代码里做错了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-01 08:00:41

您记得在web.xml中设置弹簧安全过滤链吗?

代码语言:javascript
复制
<!--  Spring security filter -->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

这不是原因,但在您的提供者实现中有一些错误。

代码语言:javascript
复制
 if(users.getPassword().equals(suppliedPasswordHash)){
            throw new BadCredentialsException("Invalid credentials");
        }
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(users, null);

首先,if中的条件是不正确的,这应该正好相反:

代码语言:javascript
复制
 if(!users.getPassword().equals(suppliedPasswordHash)){
            throw new BadCredentialsException("Invalid credentials");
        }

创建UsernamePasswordAuthenticationToken的下一行必须不同,一旦用户通过身份验证,您必须在调用构造函数时创建设置GrantedAuthorities的令牌。如果用户中的userType字段是与spring-security中指定的ROLE_admin匹配的权限,则必须以这种方式进行更多的操作:

代码语言:javascript
复制
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(user.getUserType()));
UsernamePasswordAuthenticationToken token = 
      new UsernamePasswordAuthenticationToken(users, null, authorities);

如果不这样做,则提供程序将返回一个未授予访问严格性的授权对象

票数 3
EN

Stack Overflow用户

发布于 2016-03-01 07:49:19

我认为问题在于,春季安全表单登录过滤器的登录处理与表单的post url不匹配。

在您的form-login -tag中,您没有设置login-processing-url参数,因此它使用它的默认/login *。

但是在您的html登录表单中,您使用了/j_spring_security_check。所以他们都不相配。

因此,您必须在spring配置或html表单中更正该参数。(由于下面的说明,我建议将html表单post url更改为/login,但也会使参数在配置中显示出来)

*在SpringSecurity4.0中,默认值从/j_spring_security_check更改为/login,在这里有许多“旧”教程不再起作用。

@见:http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-xml.html#m3to4-xmlnamespace-form-login

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35716136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档