Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.08 KB | None | 0 0
  1. @EnableWebSecurity
  2. @EnableJpaRepositories(basePackageClasses = AccountRepo.class)
  3. @Configuration
  4. @EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
  5. public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
  6.  
  7. @Autowired
  8. private UserDetailsService userDetailsService;
  9.  
  10. @Override
  11. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  12. auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
  13. }
  14.  
  15. @Override
  16. protected void configure(HttpSecurity http) throws Exception {
  17.  
  18. http
  19. .cors()
  20. .and()
  21. .csrf().disable()
  22.  
  23. // add filters
  24. .addFilter(new JWTAuthenticationFilter(authenticationManager()))
  25. .addFilter(new JWTAuthorizationFilter(authenticationManager()))
  26.  
  27. // don't create session
  28. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
  29.  
  30. .authorizeRequests()
  31. .antMatchers(authenticationUrl).permitAll()
  32. .anyRequest().authenticated()
  33. .and()
  34.  
  35. .csrf().disable();
  36. }
  37.  
  38. @Bean(name="passwordEncoder")
  39. public PasswordEncoder passwordEncoder() {
  40. return new BCryptPasswordEncoder();
  41. }
  42.  
  43. @Bean
  44. CorsConfigurationSource corsConfigurationSource() {
  45. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  46. source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
  47. return source;
  48. }
  49.  
  50. }
  51.  
  52. public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  53.  
  54. private AuthenticationManager authenticationManager;
  55.  
  56. public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
  57. this.authenticationManager = authenticationManager;
  58. }
  59.  
  60. @Override
  61. public Authentication attemptAuthentication(HttpServletRequest req,
  62. HttpServletResponse res) throws AuthenticationException {
  63. try {
  64. AuthenticationRequest creds = new ObjectMapper()
  65. .readValue(req.getInputStream(), AuthenticationRequest.class);
  66.  
  67. return authenticationManager.authenticate(
  68. new UsernamePasswordAuthenticationToken(
  69. creds.getEmail(),
  70. creds.getPassword(),
  71. new ArrayList<>())
  72. );
  73. } catch (IOException e) {
  74. throw new RuntimeException(e);
  75. }
  76. }
  77.  
  78. @Override
  79. protected void successfulAuthentication(HttpServletRequest req,
  80. HttpServletResponse res,
  81. FilterChain chain,
  82. Authentication auth) throws IOException, ServletException {
  83. String token = Jwts.builder()
  84. .setSubject(((User) auth.getPrincipal()).getUsername())
  85. .setExpiration(Date.from(OffsetDateTime.now().plusMinutes(EXPIRATION_TIME).toInstant()))
  86. .signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
  87. .compact();
  88. res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
  89. }
  90. }
  91.  
  92. @Service
  93. public class UserDetailsServiceImpl implements UserDetailsService {
  94.  
  95. @Autowired
  96. private AccountService service;
  97.  
  98. @Override
  99. public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
  100. VAccount account = service.getAccountByEmail(email);
  101. if(account == null) {
  102. throw new UsernameNotFoundException("no user found with email '" + email + "'");
  103. }
  104.  
  105. Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
  106. for (VRole role : account.getRoles()){
  107. System.out.println(role.getName().toString());
  108. grantedAuthorities.add(new SimpleGrantedAuthority(role.getName().toString()));
  109. }
  110.  
  111. return new org.springframework.security.core.userdetails.User(account.getEmail(), account.getPassHash(), grantedAuthorities);
  112. }
  113.  
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement