简体   繁体   中英

How to use Spring HttpSecurity without formLogin

I have SecurityConfig like:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuthProviderByIP authProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
{
    auth.authenticationProvider(authProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/public").permitAll()
            .antMatchers("/private").hasRole("ADMIN")
            .antMatchers("/**").permitAll();
}

}

And AuthProviderByIP like this:

@Component
public class AuthProviderByIP implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// making own Authentication object
}

@Override
public boolean supports(Class<?> aClass) {
    return true;
}

}

And when I'm trying to get /public resource it works fine But when trying to get /private resource it just return forbidden page. I checked it with debug and authenticate(...) method is not even invoked.

When googling there is only HttpSecurity configuring with .formLogin().and().httpBasic()

But I need not formLogin right now. How to configure it without formLogin?

Spring Security stores the Authentication object in SecurityContextHolder . Set it manuallly, if you don't want a form login or a Basic authentication. From the docs :

Authentication request = new UsernamePasswordAuthenticationToken(name, password);
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);

You can disable Form-Login and Basic-Auth in the HttpSecurity configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
    ...
    .httpBasic().disable()
    .formLogin().disable();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM