簡體   English   中英

Spring安全自定義登錄URL

[英]Spring security custom login url

我有以下Sprring網絡應用程序:

@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配置實現此行為?

更新:

@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:對我來說正確的解決方案:

  1. 從身份驗證配置中刪除登錄URL
  2. 添加異常處理程序以在身份驗證錯誤時禁用重定向
  3. 添加成功處理程序以發送用戶有效的json響應
  4. 使用http POST進行app / login
  5. Web配置中的@EnableGlobalMethodSecurity(securedEnabled = true),以便在控制器中允許@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)**;
}

你需要像這樣使用WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .logout()
            .logoutUrl("/myurl/logout")
            .and()
        .formLogin()
            .loginPage("/myurl/login")
            .defaultSuccessUrl("/myurl/login?success");
}    
}

每個東西都在文檔https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-form中解釋

您需要實現自定義AuthenticationProvider。 就像是:

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(customAuthenticationProvider());
}

@Bean
AuthenticationProvider customAuthenticationProvider() {
    CustomAuthenticationProvider impl = new CustomAuthenticationProvider();
    impl.setUserDetailsService(customUserDetailsService());
    /* other properties etc */
    return impl ;
}

@Bean   
UserDetailsService customUserDetailsService() {
    /* custom UserDetailsService code here */
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM