Lua*_*pos 3 java spring spring-mvc spring-security
我有两个关于 Spring Security 的问题。我在网上进行了大量研究,但对于我的问题而言,答案要么是肤浅的,要么是过于复杂,导致没有太大帮助。我正在尝试在应用 Java 配置策略(完全无 xml)的应用程序中使用 Spring Security。
第一种情况 我有一个扩展 WebSecurityConfigurerAdapter 的 SecurityConfiguration 类。在那里,我有我的自动装配的 loginService(它实现了 UserDetailsService)并且我已经将 AuthenticationManagerBuilder 的 UserDetailsService 定义为我的 LoginService。
当我尝试使用我的表单登录时,LoginService 成功获取用户(根据提供的用户名和密码),但不知何故身份验证失败,我在浏览器中收到来自 Tomcat 的 403 - Access Denied 消息。
第二种情况 为了解决上一个问题,我创建了一个自定义 AuthenticationProvider 并将其注入到我的 SecurityConfiguration 中。但是,当我尝试登录时,authenticate() 方法甚至不起作用。
有没有人可以帮助我?先感谢您
安全配置类
@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 );
}
}
Run Code Online (Sandbox Code Playgroud)
登录服务类
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
OBS:这里粘贴的SecurityConfiguration没有注入AuthProvider,但作为信息,configureGlobal方法应该是这样的
@Autowired
private AuthProvider authProvider;
@Autowired
public void configureGlobal ( AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
Run Code Online (Sandbox Code Playgroud)
问题解决了!似乎 HttpSecurity 的 hasRole() 方法检查角色是否采用“ROLE_”格式(例如“ROLE_ADMIN”),并且我的授予权限列表仅返回角色名称(例如“ADMIN”)。就是这样。
| 归档时间: |
|
| 查看次数: |
2574 次 |
| 最近记录: |