我有以下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 –