Spring Security:AuthenticationProvider和UserDetailsS​​ervice无法按预期工作

时间:2015-11-03 22:05:19

标签: java spring spring-mvc spring-security

我有两个关于Spring Security的问题。我在网上做了很多研究,但答案要么肤浅,要么太复杂,导致我的问题没什么帮助。我正在尝试在我的应用程序中使用Spring配置策略(完全不需要xml)。

第一个案例 我有一个扩展WebSecurityConfigurerAdapter的SecurityConfiguration类。我已经获得了自动连接的loginService(实现UserDetailsS​​ervice),并且我已将AuthenticationManagerBuilder的UserDetailsS​​ervice定义为我的LoginService。

当我尝试使用我的表单登录时,LoginService成功获取用户(根据提供的用户名和密码),但不知何故认证失败,我在浏览器中收到来自Tomcat的403 - 拒绝访问消息。

第二个案例 为了解决上一个问题,我创建了一个自定义AuthenticationProvider并将其注入我的SecurityConfiguration。但是,当我尝试登录时,方法authenticate()甚至无效。

有没有人可以帮助我?提前谢谢

SecurityConfiguration类

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

private final String ADMIN_ROLE = "ADMIN";
private final String EMPLOYEE_ROLE = "EMPLOYEE";

@Autowired
private LoginService loginService;

@Autowired
public void configureGlobal ( AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(loginService);
}

@Override
public void configure( WebSecurity web ) throws Exception {

    web.ignoring().antMatchers("/resources/**");
}

@Override
public void configure( HttpSecurity http ) throws Exception {

    http

        .authorizeRequests()
            .antMatchers("/login**", "/doLogin**").permitAll()
            .antMatchers("/admin", "/admin/**").hasRole(ADMIN_ROLE)
            .anyRequest().authenticated()
            .and()
        .requiresChannel()
            .anyRequest().requiresSecure()
            .and()
        .formLogin()
            .loginPage( "/login" )
            .loginProcessingUrl( "/doLogin" )
            .defaultSuccessUrl( "/admin" )
            .failureUrl( "/login?err=1" )
            .usernameParameter( "username" )
            .passwordParameter( "password" )
            .and()

        // This is where the logout page and process is configured. The logout-url is the URL to send
        // the user to in order to logout, the logout-success-url is where they are taken if the logout
        // is successful, and the delete-cookies and invalidate-session make sure that we clean up after logout
        .logout()
            .logoutRequestMatcher( new AntPathRequestMatcher( "/logout" ) )
            .logoutSuccessUrl( "/login?out=1" )
            .deleteCookies( "JSESSIONID" )
            .invalidateHttpSession( true )
            .and()

        // The session management is used to ensure the user only has one session. This isn't
        // compulsory but can add some extra security to your application.
        .sessionManagement()
            .invalidSessionUrl( "/login" )
            .maximumSessions( 1 );
}

}

LoginService类

@Service("loginService")
public class LoginService implements UserDetailsService{

@Autowired
private HibernateUserDAO hibernateUserDAO;

@Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {

    User user = new User();
    user.setUsername(username);

    List<User> result = hibernateUserDAO.get(user);

    user = result.get(0);
    return user;
}
}

AuthProvider类

@Component("authProvider")
public class AuthProvider implements AuthenticationProvider {


@Autowired
private LoginService loginService;


@Override
public Authentication authenticate(Authentication auth)
        throws AuthenticationException {

    String username = auth.getName();
    String password = auth.getCredentials().toString();
    System.out.println(username + " " + password);

    UserDetails user = loginService.loadUserByUsername(username);
    System.out.println(user);
    if(user != null){

        Authentication token = new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities());

        return token;
    }
    return null;
}

@Override
public boolean supports(Class<?> arg0) {
    // TODO Auto-generated method stub
    return false;
}

}

OBS:此处粘贴的SecurityConfiguration没有注入AuthProvider,但是作为一个信息,configureGlobal方法应该是这样的

@Autowired
private AuthProvider authProvider;

@Autowired
public void configureGlobal ( AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(authProvider);
}

1 个答案:

答案 0 :(得分:4)

问题解决了!看来HttpSecurity的hasRole()方法检查角色是否为“ROLE_”格式(例如“ROLE_ADMIN”),而我的授权机构列表只返回角色名称(例如“ADMIN”)。而已。