Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ApiService
- @Injectable()
- export class ApiService {
- private server = "http://localhost:8080/";
- private httpOptions;
- constructor(private http: HttpClient) {
- this.httpOptions = new Headers();
- this.httpOptions.append('Content-Type', 'application/json');
- }
- login(user){
- return this.http.post("http://localhost:8080/login", JSON.stringify(user),{headers : this.httpOptions}).subscribe(
- (res) => console.log(res)
- );
- }
- WebSecurityConfig
- @EnableWebSecurity
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- //line below is for seeing h2 database console in browser
- .headers().frameOptions().disable()
- .and()
- .csrf().disable()
- .authorizeRequests()
- .antMatchers("/","/h2/*").permitAll()
- .antMatchers( HttpMethod.POST,"/login").permitAll()
- .anyRequest().authenticated()
- .and()
- // We filter the api/login requests
- .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
- UsernamePasswordAuthenticationFilter.class)
- // And filter other requests to check the presence of JWT in header
- .addFilterBefore(new JWTAuthenticationFilter(),
- UsernamePasswordAuthenticationFilter.class)
- .cors();
- }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- // Create a default account
- auth.inMemoryAuthentication()
- .withUser("admin")
- .password("pass")
- .roles("ADMIN");
- }
- }
- MyCorsFilter
- @Component
- @Order(Ordered.HIGHEST_PRECEDENCE)
- public class MyCorsFilter implements Filter {
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
- HttpServletResponse response = (HttpServletResponse) servletResponse;
- HttpServletRequest request = (HttpServletRequest) servletRequest;
- response.setHeader("Access-Control-Allow-Origin", "*");
- response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
- filterChain.doFilter(request, response);
- }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- @Override
- public void destroy() {
- }
- }
- JWTLoginFilter
- public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
- private final Log logger = LogFactory.getLog(getClass());
- public JWTLoginFilter(String url, AuthenticationManager authManager) {
- super(new AntPathRequestMatcher(url));
- setAuthenticationManager(authManager);
- }
- @Override
- public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
- throws AuthenticationException, IOException, ServletException {
- //objectmapper is creating pojo object from json and next it is checking if credentials are correct
- ObjectMapper objectMapper = new ObjectMapper();
- objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- AccountCredentials creds = objectMapper
- .readValue(req.getInputStream(), AccountCredentials.class);
- logger.info(creds.getUsername());
- logger.info(creds.getPassword());
- return getAuthenticationManager().authenticate(
- new UsernamePasswordAuthenticationToken(
- creds.getUsername(),
- creds.getPassword(),
- Collections.emptyList()
- )
- );
- }
- //if credentials above are correct tokenauthenticationservice is creating new token
- @Override
- protected void successfulAuthentication(
- HttpServletRequest req,
- HttpServletResponse res, FilterChain chain,
- Authentication auth) throws IOException, ServletException {
- TokenAuthenticationService
- .addAuthentication(res, auth.getName());
- }
- }
- JWTAuthenticationFilter
- public class JWTAuthenticationFilter extends GenericFilterBean {
- @Override
- public void doFilter(ServletRequest request,
- ServletResponse response,
- FilterChain filterChain)
- throws IOException, ServletException {
- Authentication authentication = TokenAuthenticationService
- .getAuthentication((HttpServletRequest)request);
- SecurityContextHolder.getContext()
- .setAuthentication(authentication);
- filterChain.doFilter(request,response);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement