我有以下Sprring Web应用程序:春季安全自定义登录网址
@Secured({"ROLE_ADMIN"})
@RequestMapping(value = "data/{id}", method = RequestMethod.GET)
public Object getData(@RequestPath String id)
@RequestMapping(value = "login", method = RequestMethod.GET)
public Object login(@RequestParam String username, @RequestParam String password)
在登录我需要调用另一台服务器,传递凭据并取回角色,然后让Spring知道用于传入用户这些角色。 登录客户端如果通过ROLE_ADMIN的授权,可以使用getData方法。
如何使用java配置实现此行为?
UPDATE:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public AuthenticationProvider authenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
}
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final Logger logger = LogFactory.getLogger();
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
log.debug("name=" + name + " password=" + password);
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
return auth;
}
@Override
public boolean supports(Class<?> authentication) {
logger.debug("supports authentication=" + authentication);
return true;
}
}
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
但我可以从日志CustomAuthenticationProvider.authenticate永远不会被调用看到。 我错过了什么吗? 谢谢。
更新2:我正确的解决办法:
- 删除登录网址从认证配置
- 附加异常处理程序中的身份验证错误的情况下禁用重定向
- 添加成功处理程序发送用户有效的JSON响应
- 使用http POST进行应用/登录
- @EnableGlobalMethodSecurity(securedEnabled = true)在web配置中,以便允许控制器中的@Secured注释。 感谢您的所有提示。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
**.anyRequest().authenticated()**
.and().formLogin()
.loginProcessingUrl("/login").usernameParameter("username")
.passwordParameter("password")
**.successHandler(authenticationSuccessHandler)**.failureHandler(authenticationFailureHandler)
.and().csrf().disable().**exceptionHandling()
.authenticationEntryPoint(errorsAuthenticationEntryPoint)**;
}
感谢您的答复。我实现了这一点,也为登录网址添加了许可证,但我的CustomAuthenticationProvider不起作用。我在那里放了一些原木,因为我可以看到它从来没有被春天叫过。 – rholovakha
请参阅此链接 - 它解释了所有内容:http://docs.spring.io/spring-security/site/docs/current/guides/html5/form.html –