Advertisement
Guest User

Untitled

a guest
Aug 5th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.52 KB | None | 0 0
  1. @RestController
  2. @RequestMapping("/private")
  3. public class AccountController {
  4.  
  5. @GetMapping("/getUserInfo")
  6. public @ResponseBody
  7. String getUserInfo(@AuthenticationPrincipal final Account user) {//user == null
  8. return user.getUsername();
  9. }
  10. }
  11.  
  12. @EnableWebSecurity
  13. public class WebSecurity extends WebSecurityConfigurerAdapter {
  14. private AccountDetailsServiceImpl accountDetailsService;
  15. private BCryptPasswordEncoder bCryptPasswordEncoder;
  16.  
  17. public WebSecurity(AccountDetailsServiceImpl accountDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
  18. this.accountDetailsService = accountDetailsService;
  19. this.bCryptPasswordEncoder = bCryptPasswordEncoder;
  20. }
  21.  
  22.  
  23. @Override
  24. protected void configure(HttpSecurity http) throws Exception {
  25. http.cors().and().csrf().disable().authorizeRequests()
  26. .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
  27. .anyRequest().authenticated()
  28. .and()
  29. .addFilter(new JWTAuthenticationFilter(authenticationManager()))
  30. .addFilter(new JWTAuthorizationFilter(authenticationManager()))
  31. // this disables session creation on Spring Security
  32. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  33. }
  34.  
  35. @Override
  36. public void configure(AuthenticationManagerBuilder auth) throws Exception {
  37. auth.userDetailsService(accountDetailsService).passwordEncoder(bCryptPasswordEncoder);
  38. }
  39.  
  40. @Bean
  41. CorsConfigurationSource corsConfigurationSource() {
  42. final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  43. source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
  44. return source;
  45. }
  46. }
  47.  
  48. @Service
  49. public class AccountDetailsServiceImpl implements UserDetailsService {
  50. private AccountRepository applicationUserRepository;
  51.  
  52. public AccountDetailsServiceImpl(AccountRepository applicationUserRepository) {
  53. this.applicationUserRepository = applicationUserRepository;
  54. }
  55.  
  56. @Override
  57. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  58. Optional<Account> applicationUser = applicationUserRepository.findByUsername(username);
  59. if (applicationUser == null) {
  60. throw new UsernameNotFoundException(username);
  61. }
  62. User user = new User(applicationUser.get().getUsername(), applicationUser.get().getPassword(), emptyList());
  63. return user;
  64. }
  65. }
  66.  
  67. @Entity(name = "Account")
  68. @Table(name = "account")
  69. public class Account implements UserDetails {
  70.  
  71. @Id
  72. @GeneratedValue(strategy=GenerationType.IDENTITY)
  73. private Long id;
  74.  
  75. private String username;
  76.  
  77. private String password;
  78.  
  79.  
  80. private Account() { }
  81.  
  82. public Account(final String username, final String password) {
  83. this.username = username;
  84. this.password = password;
  85. }
  86.  
  87.  
  88. @Override
  89. public Collection<GrantedAuthority> getAuthorities() {
  90. return new ArrayList<>();
  91. }
  92.  
  93. @JsonIgnore
  94. @Override
  95. public boolean isAccountNonExpired() {
  96. return true;
  97. }
  98.  
  99. @JsonIgnore
  100. @Override
  101. public boolean isAccountNonLocked() {
  102. return true;
  103. }
  104.  
  105. @JsonIgnore
  106. @Override
  107. public boolean isCredentialsNonExpired() {
  108. return true;
  109. }
  110.  
  111. @Override
  112. public boolean isEnabled() {
  113. return true;
  114. }
  115.  
  116. public Long getId() {
  117. return id;
  118. }
  119.  
  120. @Override
  121. public String getUsername() {
  122. return username;
  123. }
  124.  
  125. @Override
  126. public String getPassword() {
  127. return password;
  128. }
  129.  
  130. public void setPassword(String password) {
  131. this.password = password;
  132. }
  133. }
  134.  
  135. public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
  136.  
  137.  
  138. private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
  139. private AuthenticationManager authenticationManager;
  140.  
  141. public JWTAuthorizationFilter(AuthenticationManager authManager) {
  142. super(authManager);
  143. this.authenticationManager = authManager;
  144. }
  145.  
  146. @Override
  147. protected void doFilterInternal(HttpServletRequest req,
  148. HttpServletResponse res,
  149. FilterChain chain) throws IOException, ServletException {
  150. String header = req.getHeader(HEADER_STRING);
  151.  
  152. if (header == null || !header.startsWith(TOKEN_PREFIX)) {
  153. chain.doFilter(req, res);
  154. return;
  155. }
  156.  
  157.  
  158. UsernamePasswordAuthenticationToken authRequest = getAuthentication(req);
  159.  
  160. authRequest.setDetails(
  161. this.authenticationDetailsSource.buildDetails(req));
  162. Authentication authResult = this.authenticationManager
  163. .authenticate(authRequest);
  164.  
  165. SecurityContextHolder.getContext().setAuthentication(authResult);
  166.  
  167.  
  168. onSuccessfulAuthentication(req, res, authResult);
  169.  
  170.  
  171.  
  172. chain.doFilter(req, res);
  173. }
  174.  
  175. private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
  176. String token = request.getHeader(HEADER_STRING);
  177. if (token != null) {
  178.  
  179. String user = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody().getSubject();
  180.  
  181.  
  182. if (user != null) {
  183. return new UsernamePasswordAuthenticationToken(user, "password", new ArrayList<>()); //hardcoded password
  184. }
  185. return null;
  186. }
  187. return null;
  188. }
  189. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement