gpt4 book ai didi

java - Spring 安全 : AuthenticationProvider and UserDetailsService not working as expected

转载 作者:行者123 更新时间:2023-11-30 06:57:22 27 4
gpt4 key购买 nike

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

第一个案例我有一个扩展 WebSecurityConfigurerAdapter 的 SecurityConfiguration 类。在那里我有我的自动连接的登录服务(它实现了 UserDetailsS​​ervice)并且我已经将 AuthenticationManagerBuilder 的 UserDetailsS​​ervice 定义为我的登录服务。

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

第二种情况为了解决之前的问题,我创建了一个自定义 AuthenticationProvider 并将其注入(inject)到我的 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 );
}

}

登录服务类

@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并没有注入(inject)AuthProvider,但是作为信息,configureGlobal方法应该是这样的

@Autowired
private AuthProvider authProvider;

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

auth.authenticationProvider(authProvider);
}

最佳答案

问题解决了!似乎 HttpSecurity 的 hasRole() 方法检查角色是否采用“ROLE_”格式(例如“ROLE_ADMIN”),而我的授权权限列表仅返回角色名称(例如“ADMIN”)。就是这样。

关于java - Spring 安全 : AuthenticationProvider and UserDetailsService not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509978/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com