Advertisement
Guest User

Untitled

a guest
Dec 12th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. protected void configure(HttpSecurity http) throws Exception {
  2. http
  3. .authorizeRequests()
  4. .anyRequest().authenticated()
  5. .and()
  6. .requestCache()
  7. .requestCache(new NullRequestCache())
  8. .and()
  9. .httpBasic();
  10. }
  11.  
  12. import org.springframework.security.authentication.AuthenticationProvider;
  13. import org.springframework.security.authentication.BadCredentialsException;
  14. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  15. import org.springframework.security.core.Authentication;
  16. import org.springframework.security.core.AuthenticationException;
  17. import org.springframework.security.core.authority.AuthorityUtils;
  18.  
  19. public class RestAuthenticationProvider implements AuthenticationProvider {
  20.  
  21. public Authentication authenticate(Authentication authentication)
  22. throws AuthenticationException {
  23. UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
  24.  
  25. String username = token.getName();
  26. String password = (String) token.getCredentials();
  27.  
  28. // validate making REST call
  29. boolean success = true;
  30. // likely your REST call will return the roles for the user
  31. String[] roles = new String[] { "ROLE_USER" };
  32.  
  33. if(!success) {
  34. throw new BadCredentialsException("Bad credentials");
  35. }
  36.  
  37. return new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(roles));
  38. }
  39.  
  40. public boolean supports(Class<?> authentication) {
  41. return (UsernamePasswordAuthenticationToken.class
  42. .isAssignableFrom(authentication));
  43. }
  44.  
  45. }
  46.  
  47. @EnableWebSecurity
  48. @Configuration
  49. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  50. ...
  51.  
  52. @Bean
  53. public RestAuthenticationProvider restAuthenticationProvider() {
  54. return new RestAuthenticationProvider();
  55. }
  56.  
  57. @Autowired
  58. public void configureGlobal(AuthenticationManagerBuilder auth, AuthenticationProvider provider) throws Exception {
  59. auth
  60. .authenticationProvider(provider);
  61. }
  62. }
  63.  
  64. http.formLogin().failureHandler(authenticationFailureHandler()).permitAll();
  65.  
  66. private AuthenticationFailureHandler authenticationFailureHandler() {
  67. return new AuthenticationFailureHandler();
  68. }
  69.  
  70. public class AuthenticationFailureHandler
  71. extends SimpleUrlAuthenticationFailureHandler {
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement