Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .requestCache()
- .requestCache(new NullRequestCache())
- .and()
- .httpBasic();
- }
- import org.springframework.security.authentication.AuthenticationProvider;
- import org.springframework.security.authentication.BadCredentialsException;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.core.authority.AuthorityUtils;
- public class RestAuthenticationProvider implements AuthenticationProvider {
- public Authentication authenticate(Authentication authentication)
- throws AuthenticationException {
- UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
- String username = token.getName();
- String password = (String) token.getCredentials();
- // validate making REST call
- boolean success = true;
- // likely your REST call will return the roles for the user
- String[] roles = new String[] { "ROLE_USER" };
- if(!success) {
- throw new BadCredentialsException("Bad credentials");
- }
- return new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(roles));
- }
- public boolean supports(Class<?> authentication) {
- return (UsernamePasswordAuthenticationToken.class
- .isAssignableFrom(authentication));
- }
- }
- @EnableWebSecurity
- @Configuration
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- ...
- @Bean
- public RestAuthenticationProvider restAuthenticationProvider() {
- return new RestAuthenticationProvider();
- }
- @Autowired
- public void configureGlobal(AuthenticationManagerBuilder auth, AuthenticationProvider provider) throws Exception {
- auth
- .authenticationProvider(provider);
- }
- }
- http.formLogin().failureHandler(authenticationFailureHandler()).permitAll();
- private AuthenticationFailureHandler authenticationFailureHandler() {
- return new AuthenticationFailureHandler();
- }
- public class AuthenticationFailureHandler
- extends SimpleUrlAuthenticationFailureHandler {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement