Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @RestController
- @RequestMapping("/private")
- public class AccountController {
- @GetMapping("/getUserInfo")
- public @ResponseBody
- String getUserInfo(@AuthenticationPrincipal final Account user) {//user == null
- return user.getUsername();
- }
- }
- @EnableWebSecurity
- public class WebSecurity extends WebSecurityConfigurerAdapter {
- private AccountDetailsServiceImpl accountDetailsService;
- private BCryptPasswordEncoder bCryptPasswordEncoder;
- public WebSecurity(AccountDetailsServiceImpl accountDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
- this.accountDetailsService = accountDetailsService;
- this.bCryptPasswordEncoder = bCryptPasswordEncoder;
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.cors().and().csrf().disable().authorizeRequests()
- .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
- .anyRequest().authenticated()
- .and()
- .addFilter(new JWTAuthenticationFilter(authenticationManager()))
- .addFilter(new JWTAuthorizationFilter(authenticationManager()))
- // this disables session creation on Spring Security
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
- }
- @Override
- public void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(accountDetailsService).passwordEncoder(bCryptPasswordEncoder);
- }
- @Bean
- CorsConfigurationSource corsConfigurationSource() {
- final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
- return source;
- }
- }
- @Service
- public class AccountDetailsServiceImpl implements UserDetailsService {
- private AccountRepository applicationUserRepository;
- public AccountDetailsServiceImpl(AccountRepository applicationUserRepository) {
- this.applicationUserRepository = applicationUserRepository;
- }
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- Optional<Account> applicationUser = applicationUserRepository.findByUsername(username);
- if (applicationUser == null) {
- throw new UsernameNotFoundException(username);
- }
- User user = new User(applicationUser.get().getUsername(), applicationUser.get().getPassword(), emptyList());
- return user;
- }
- }
- @Entity(name = "Account")
- @Table(name = "account")
- public class Account implements UserDetails {
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- private Long id;
- private String username;
- private String password;
- private Account() { }
- public Account(final String username, final String password) {
- this.username = username;
- this.password = password;
- }
- @Override
- public Collection<GrantedAuthority> getAuthorities() {
- return new ArrayList<>();
- }
- @JsonIgnore
- @Override
- public boolean isAccountNonExpired() {
- return true;
- }
- @JsonIgnore
- @Override
- public boolean isAccountNonLocked() {
- return true;
- }
- @JsonIgnore
- @Override
- public boolean isCredentialsNonExpired() {
- return true;
- }
- @Override
- public boolean isEnabled() {
- return true;
- }
- public Long getId() {
- return id;
- }
- @Override
- public String getUsername() {
- return username;
- }
- @Override
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
- private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
- private AuthenticationManager authenticationManager;
- public JWTAuthorizationFilter(AuthenticationManager authManager) {
- super(authManager);
- this.authenticationManager = authManager;
- }
- @Override
- protected void doFilterInternal(HttpServletRequest req,
- HttpServletResponse res,
- FilterChain chain) throws IOException, ServletException {
- String header = req.getHeader(HEADER_STRING);
- if (header == null || !header.startsWith(TOKEN_PREFIX)) {
- chain.doFilter(req, res);
- return;
- }
- UsernamePasswordAuthenticationToken authRequest = getAuthentication(req);
- authRequest.setDetails(
- this.authenticationDetailsSource.buildDetails(req));
- Authentication authResult = this.authenticationManager
- .authenticate(authRequest);
- SecurityContextHolder.getContext().setAuthentication(authResult);
- onSuccessfulAuthentication(req, res, authResult);
- chain.doFilter(req, res);
- }
- private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
- String token = request.getHeader(HEADER_STRING);
- if (token != null) {
- String user = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody().getSubject();
- if (user != null) {
- return new UsernamePasswordAuthenticationToken(user, "password", new ArrayList<>()); //hardcoded password
- }
- return null;
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement