Advertisement
Guest User

jwt

a guest
Dec 28th, 2017
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.91 KB | None | 0 0
  1. ApiService
  2.  
  3.     @Injectable()
  4. export class ApiService {
  5.  
  6.   private server = "http://localhost:8080/";
  7.   private httpOptions;
  8.  
  9.   constructor(private http: HttpClient) {
  10.    this.httpOptions = new Headers();
  11.     this.httpOptions.append('Content-Type', 'application/json');
  12.   }
  13.  
  14.   login(user){
  15.     return this.http.post("http://localhost:8080/login", JSON.stringify(user),{headers : this.httpOptions}).subscribe(
  16.       (res) => console.log(res)
  17.  
  18.     );
  19.   }
  20.  
  21. WebSecurityConfig
  22.  
  23. @EnableWebSecurity
  24. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  25.  
  26.     @Override
  27.     protected void configure(HttpSecurity http) throws Exception {
  28.         http
  29.  
  30.                 //line below is for seeing h2 database console in browser
  31.                 .headers().frameOptions().disable()
  32.                 .and()
  33.                 .csrf().disable()
  34.  
  35.                 .authorizeRequests()
  36.                 .antMatchers("/","/h2/*").permitAll()
  37.                 .antMatchers( HttpMethod.POST,"/login").permitAll()
  38.                 .anyRequest().authenticated()
  39.                 .and()
  40.                 // We filter the api/login requests
  41.                 .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
  42.                         UsernamePasswordAuthenticationFilter.class)
  43.  
  44.                 // And filter other requests to check the presence of JWT in header
  45.                 .addFilterBefore(new JWTAuthenticationFilter(),
  46.                         UsernamePasswordAuthenticationFilter.class)
  47.                 .cors();
  48.     }
  49.  
  50.     @Override
  51.     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  52.         // Create a default account
  53.         auth.inMemoryAuthentication()
  54.                 .withUser("admin")
  55.                 .password("pass")
  56.                 .roles("ADMIN");
  57.     }
  58. }
  59.  
  60.  
  61. MyCorsFilter
  62.  
  63. @Component
  64. @Order(Ordered.HIGHEST_PRECEDENCE)
  65. public class MyCorsFilter implements Filter {
  66.  
  67.  
  68.     @Override
  69.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  70.         HttpServletResponse response = (HttpServletResponse) servletResponse;
  71.         HttpServletRequest request = (HttpServletRequest) servletRequest;
  72.         response.setHeader("Access-Control-Allow-Origin", "*");
  73.         response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
  74.  
  75.         filterChain.doFilter(request, response);
  76.     }
  77.  
  78.     @Override
  79.     public void init(FilterConfig filterConfig) throws ServletException {
  80.  
  81.     }
  82.  
  83.     @Override
  84.     public void destroy() {
  85.  
  86.     }
  87.  
  88. }
  89.  
  90.  
  91. JWTLoginFilter
  92.  
  93. public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
  94.  
  95.     private final Log logger = LogFactory.getLog(getClass());
  96.  
  97.     public JWTLoginFilter(String url, AuthenticationManager authManager) {
  98.         super(new AntPathRequestMatcher(url));
  99.         setAuthenticationManager(authManager);
  100.     }
  101.  
  102.     @Override
  103.     public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
  104.             throws AuthenticationException, IOException, ServletException {
  105.  
  106.         //objectmapper is creating pojo object from json and next it is checking if credentials are correct
  107.         ObjectMapper objectMapper = new ObjectMapper();
  108.         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  109.         AccountCredentials creds = objectMapper
  110.                 .readValue(req.getInputStream(), AccountCredentials.class);
  111.         logger.info(creds.getUsername());
  112.         logger.info(creds.getPassword());
  113.         return getAuthenticationManager().authenticate(
  114.                 new UsernamePasswordAuthenticationToken(
  115.                         creds.getUsername(),
  116.                         creds.getPassword(),
  117.                         Collections.emptyList()
  118.                 )
  119.         );
  120.     }
  121.  
  122.     //if credentials above are correct tokenauthenticationservice is creating new token
  123.     @Override
  124.     protected void successfulAuthentication(
  125.             HttpServletRequest req,
  126.             HttpServletResponse res, FilterChain chain,
  127.             Authentication auth) throws IOException, ServletException {
  128.         TokenAuthenticationService
  129.                 .addAuthentication(res, auth.getName());
  130.     }
  131. }
  132.  
  133.  
  134. JWTAuthenticationFilter
  135.  
  136. public class JWTAuthenticationFilter extends GenericFilterBean {
  137.  
  138.     @Override
  139.     public void doFilter(ServletRequest request,
  140.                          ServletResponse response,
  141.                          FilterChain filterChain)
  142.             throws IOException, ServletException {
  143.  
  144.         Authentication authentication = TokenAuthenticationService
  145.                 .getAuthentication((HttpServletRequest)request);
  146.  
  147.         SecurityContextHolder.getContext()
  148.                 .setAuthentication(authentication);
  149.         filterChain.doFilter(request,response);
  150.     }
  151. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement