Unable to login using JWT authentication mechanism












0














I'm working on a SpringBoot 2.0 application with Spring Web, Spring Security and using JWT for authentication purpose. There is just 1 URI path which is public and accessible by anyone except that all other URIs are protected and throws 'Access Denied' during any attempt. I can access to this public URI and create a new user in database with username and password. However, when I try to login with same credentials, I get HTTP 403 Forbidden error.



Please assist me here. Thanks



Authentication class:-



public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);

private AuthenticationManager authenticationManager;

public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
logger.info("Entering attemptAuthentication@JWTAuthenticationFilter");

try{
ApplicationUser credential = new ObjectMapper()
.readValue(request.getInputStream(), ApplicationUser.class);
logger.info("Validating Credential:: {}, {}", credential.getUsername(), credential.getPassword());

return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credential.getUsername(),
credential.getPassword(), new ArrayList<>()));

}catch(IOException io){
throw new RuntimeException(io);
}
}

@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain, Authentication authResult)
throws IOException, ServletException {
logger.info("Entering successfulAuthentication@JWTAuthenticationFilter");

String jwtToken = Jwts.builder()
.setSubject(((User) authResult.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + SecurityConstant.EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SecurityConstant.SECRET)
.compact();

logger.info("JWT Token:: {}", jwtToken);
response.addHeader(SecurityConstant.HEADER_STRING, SecurityConstant.TOKEN_PREFIX + jwtToken);

}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
logger.info("Failed authentication while attempting to access");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
}
}


Authorization class :-



public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
private static Logger logger = LoggerFactory.getLogger(JWTAuthorizationFilter.class);

public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}


/**
*
* @param request
* @param response
* @param chain
* @throws IOException
* @throws ServletException
*/
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
logger.info("Entering doFilterInternal@JWTAuthorizationFilter");

String header = request.getHeader(SecurityConstant.HEADER_STRING);
logger.info("header:: {}", header);

if(null == header || !header.startsWith(SecurityConstant.TOKEN_PREFIX)){
logger.info("chaining");
chain.doFilter(request, response);
return;
}

UsernamePasswordAuthenticationToken authentication = getAuthentication(header);
logger.info("Authentication:: {}", authentication);

SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);

}


/**
*
* @param header
* @return
*/
private UsernamePasswordAuthenticationToken getAuthentication(String header){
logger.info("Entering getAuthenticationToken@JWTAuthorizationFilter");
logger.info("token::{}", header);
if(null != header){

//Parsing JWT Token
String user = Jwts.parser()
.setSigningKey(SecurityConstant.SECRET)
.parseClaimsJws(header.replace(SecurityConstant.TOKEN_PREFIX, ""))
.getBody()
.getSubject();

logger.info("user:: {}",user);
if(null != user){
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
}


WebSecurity class:-



@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

private UserDetailsService userDetailsService;

private BCryptPasswordEncoder bCryptPasswordEncoder;


public WebSecurity(UserDetailsService userDetailsService,
BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}


@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, SecurityConstant.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);

}

@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}


Application.properties file:-



#spring.security.user.name=user
#spring.security.user.password=user

spring.data.mongodb.uri=mongodb://localhost:27017/myspringdb


PostMan test data for signup (it is working) :-



http://localhost:8080/users/sign-up



{
"id":"2",
"username":"user",
"password":"user",
"emailAddress":"abc@sample.com"
}


PostMan test data for sign-in (not working):-



http://localhost:8080/login



Header: content-type:application/json



{
"username":"user",
"password":"user"
}


And also wants to know whether Im doing correct here not by using spring-security because while running the program, the program generates a password by itself like below :-



Using generated security password: ki908a3f-00ec-98cc-bn02-823ead10f153



Should I using my own credentials which saved in database (mongodb) or this spring generated password for authentication purpose?



Thank you










share|improve this question





























    0














    I'm working on a SpringBoot 2.0 application with Spring Web, Spring Security and using JWT for authentication purpose. There is just 1 URI path which is public and accessible by anyone except that all other URIs are protected and throws 'Access Denied' during any attempt. I can access to this public URI and create a new user in database with username and password. However, when I try to login with same credentials, I get HTTP 403 Forbidden error.



    Please assist me here. Thanks



    Authentication class:-



    public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
    HttpServletResponse response) throws AuthenticationException {
    logger.info("Entering attemptAuthentication@JWTAuthenticationFilter");

    try{
    ApplicationUser credential = new ObjectMapper()
    .readValue(request.getInputStream(), ApplicationUser.class);
    logger.info("Validating Credential:: {}, {}", credential.getUsername(), credential.getPassword());

    return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credential.getUsername(),
    credential.getPassword(), new ArrayList<>()));

    }catch(IOException io){
    throw new RuntimeException(io);
    }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
    HttpServletResponse response,
    FilterChain chain, Authentication authResult)
    throws IOException, ServletException {
    logger.info("Entering successfulAuthentication@JWTAuthenticationFilter");

    String jwtToken = Jwts.builder()
    .setSubject(((User) authResult.getPrincipal()).getUsername())
    .setExpiration(new Date(System.currentTimeMillis() + SecurityConstant.EXPIRATION_TIME))
    .signWith(SignatureAlgorithm.HS512, SecurityConstant.SECRET)
    .compact();

    logger.info("JWT Token:: {}", jwtToken);
    response.addHeader(SecurityConstant.HEADER_STRING, SecurityConstant.TOKEN_PREFIX + jwtToken);

    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
    AuthenticationException failed) throws IOException, ServletException {
    logger.info("Failed authentication while attempting to access");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
    }
    }


    Authorization class :-



    public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    private static Logger logger = LoggerFactory.getLogger(JWTAuthorizationFilter.class);

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
    super(authenticationManager);
    }


    /**
    *
    * @param request
    * @param response
    * @param chain
    * @throws IOException
    * @throws ServletException
    */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
    HttpServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    logger.info("Entering doFilterInternal@JWTAuthorizationFilter");

    String header = request.getHeader(SecurityConstant.HEADER_STRING);
    logger.info("header:: {}", header);

    if(null == header || !header.startsWith(SecurityConstant.TOKEN_PREFIX)){
    logger.info("chaining");
    chain.doFilter(request, response);
    return;
    }

    UsernamePasswordAuthenticationToken authentication = getAuthentication(header);
    logger.info("Authentication:: {}", authentication);

    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(request, response);

    }


    /**
    *
    * @param header
    * @return
    */
    private UsernamePasswordAuthenticationToken getAuthentication(String header){
    logger.info("Entering getAuthenticationToken@JWTAuthorizationFilter");
    logger.info("token::{}", header);
    if(null != header){

    //Parsing JWT Token
    String user = Jwts.parser()
    .setSigningKey(SecurityConstant.SECRET)
    .parseClaimsJws(header.replace(SecurityConstant.TOKEN_PREFIX, ""))
    .getBody()
    .getSubject();

    logger.info("user:: {}",user);
    if(null != user){
    return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
    }
    return null;
    }
    return null;
    }
    }


    WebSecurity class:-



    @EnableWebSecurity
    public class WebSecurity extends WebSecurityConfigurerAdapter {

    private UserDetailsService userDetailsService;

    private BCryptPasswordEncoder bCryptPasswordEncoder;


    public WebSecurity(UserDetailsService userDetailsService,
    BCryptPasswordEncoder bCryptPasswordEncoder) {
    this.userDetailsService = userDetailsService;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf()
    .disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.POST, SecurityConstant.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);

    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
    }
    }


    Application.properties file:-



    #spring.security.user.name=user
    #spring.security.user.password=user

    spring.data.mongodb.uri=mongodb://localhost:27017/myspringdb


    PostMan test data for signup (it is working) :-



    http://localhost:8080/users/sign-up



    {
    "id":"2",
    "username":"user",
    "password":"user",
    "emailAddress":"abc@sample.com"
    }


    PostMan test data for sign-in (not working):-



    http://localhost:8080/login



    Header: content-type:application/json



    {
    "username":"user",
    "password":"user"
    }


    And also wants to know whether Im doing correct here not by using spring-security because while running the program, the program generates a password by itself like below :-



    Using generated security password: ki908a3f-00ec-98cc-bn02-823ead10f153



    Should I using my own credentials which saved in database (mongodb) or this spring generated password for authentication purpose?



    Thank you










    share|improve this question



























      0












      0








      0







      I'm working on a SpringBoot 2.0 application with Spring Web, Spring Security and using JWT for authentication purpose. There is just 1 URI path which is public and accessible by anyone except that all other URIs are protected and throws 'Access Denied' during any attempt. I can access to this public URI and create a new user in database with username and password. However, when I try to login with same credentials, I get HTTP 403 Forbidden error.



      Please assist me here. Thanks



      Authentication class:-



      public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
      private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);

      private AuthenticationManager authenticationManager;

      public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
      this.authenticationManager = authenticationManager;
      }

      @Override
      public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) throws AuthenticationException {
      logger.info("Entering attemptAuthentication@JWTAuthenticationFilter");

      try{
      ApplicationUser credential = new ObjectMapper()
      .readValue(request.getInputStream(), ApplicationUser.class);
      logger.info("Validating Credential:: {}, {}", credential.getUsername(), credential.getPassword());

      return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credential.getUsername(),
      credential.getPassword(), new ArrayList<>()));

      }catch(IOException io){
      throw new RuntimeException(io);
      }
      }

      @Override
      protected void successfulAuthentication(HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain, Authentication authResult)
      throws IOException, ServletException {
      logger.info("Entering successfulAuthentication@JWTAuthenticationFilter");

      String jwtToken = Jwts.builder()
      .setSubject(((User) authResult.getPrincipal()).getUsername())
      .setExpiration(new Date(System.currentTimeMillis() + SecurityConstant.EXPIRATION_TIME))
      .signWith(SignatureAlgorithm.HS512, SecurityConstant.SECRET)
      .compact();

      logger.info("JWT Token:: {}", jwtToken);
      response.addHeader(SecurityConstant.HEADER_STRING, SecurityConstant.TOKEN_PREFIX + jwtToken);

      }

      @Override
      protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException failed) throws IOException, ServletException {
      logger.info("Failed authentication while attempting to access");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
      }
      }


      Authorization class :-



      public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
      private static Logger logger = LoggerFactory.getLogger(JWTAuthorizationFilter.class);

      public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
      super(authenticationManager);
      }


      /**
      *
      * @param request
      * @param response
      * @param chain
      * @throws IOException
      * @throws ServletException
      */
      @Override
      protected void doFilterInternal(HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain) throws IOException, ServletException {
      logger.info("Entering doFilterInternal@JWTAuthorizationFilter");

      String header = request.getHeader(SecurityConstant.HEADER_STRING);
      logger.info("header:: {}", header);

      if(null == header || !header.startsWith(SecurityConstant.TOKEN_PREFIX)){
      logger.info("chaining");
      chain.doFilter(request, response);
      return;
      }

      UsernamePasswordAuthenticationToken authentication = getAuthentication(header);
      logger.info("Authentication:: {}", authentication);

      SecurityContextHolder.getContext().setAuthentication(authentication);
      chain.doFilter(request, response);

      }


      /**
      *
      * @param header
      * @return
      */
      private UsernamePasswordAuthenticationToken getAuthentication(String header){
      logger.info("Entering getAuthenticationToken@JWTAuthorizationFilter");
      logger.info("token::{}", header);
      if(null != header){

      //Parsing JWT Token
      String user = Jwts.parser()
      .setSigningKey(SecurityConstant.SECRET)
      .parseClaimsJws(header.replace(SecurityConstant.TOKEN_PREFIX, ""))
      .getBody()
      .getSubject();

      logger.info("user:: {}",user);
      if(null != user){
      return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
      }
      return null;
      }
      return null;
      }
      }


      WebSecurity class:-



      @EnableWebSecurity
      public class WebSecurity extends WebSecurityConfigurerAdapter {

      private UserDetailsService userDetailsService;

      private BCryptPasswordEncoder bCryptPasswordEncoder;


      public WebSecurity(UserDetailsService userDetailsService,
      BCryptPasswordEncoder bCryptPasswordEncoder) {
      this.userDetailsService = userDetailsService;
      this.bCryptPasswordEncoder = bCryptPasswordEncoder;
      }

      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
      }


      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http.cors().and().csrf()
      .disable()
      .authorizeRequests()
      .antMatchers(HttpMethod.POST, SecurityConstant.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);

      }

      @Bean
      CorsConfigurationSource corsConfigurationSource() {
      final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
      return source;
      }
      }


      Application.properties file:-



      #spring.security.user.name=user
      #spring.security.user.password=user

      spring.data.mongodb.uri=mongodb://localhost:27017/myspringdb


      PostMan test data for signup (it is working) :-



      http://localhost:8080/users/sign-up



      {
      "id":"2",
      "username":"user",
      "password":"user",
      "emailAddress":"abc@sample.com"
      }


      PostMan test data for sign-in (not working):-



      http://localhost:8080/login



      Header: content-type:application/json



      {
      "username":"user",
      "password":"user"
      }


      And also wants to know whether Im doing correct here not by using spring-security because while running the program, the program generates a password by itself like below :-



      Using generated security password: ki908a3f-00ec-98cc-bn02-823ead10f153



      Should I using my own credentials which saved in database (mongodb) or this spring generated password for authentication purpose?



      Thank you










      share|improve this question















      I'm working on a SpringBoot 2.0 application with Spring Web, Spring Security and using JWT for authentication purpose. There is just 1 URI path which is public and accessible by anyone except that all other URIs are protected and throws 'Access Denied' during any attempt. I can access to this public URI and create a new user in database with username and password. However, when I try to login with same credentials, I get HTTP 403 Forbidden error.



      Please assist me here. Thanks



      Authentication class:-



      public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
      private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);

      private AuthenticationManager authenticationManager;

      public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
      this.authenticationManager = authenticationManager;
      }

      @Override
      public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) throws AuthenticationException {
      logger.info("Entering attemptAuthentication@JWTAuthenticationFilter");

      try{
      ApplicationUser credential = new ObjectMapper()
      .readValue(request.getInputStream(), ApplicationUser.class);
      logger.info("Validating Credential:: {}, {}", credential.getUsername(), credential.getPassword());

      return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credential.getUsername(),
      credential.getPassword(), new ArrayList<>()));

      }catch(IOException io){
      throw new RuntimeException(io);
      }
      }

      @Override
      protected void successfulAuthentication(HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain, Authentication authResult)
      throws IOException, ServletException {
      logger.info("Entering successfulAuthentication@JWTAuthenticationFilter");

      String jwtToken = Jwts.builder()
      .setSubject(((User) authResult.getPrincipal()).getUsername())
      .setExpiration(new Date(System.currentTimeMillis() + SecurityConstant.EXPIRATION_TIME))
      .signWith(SignatureAlgorithm.HS512, SecurityConstant.SECRET)
      .compact();

      logger.info("JWT Token:: {}", jwtToken);
      response.addHeader(SecurityConstant.HEADER_STRING, SecurityConstant.TOKEN_PREFIX + jwtToken);

      }

      @Override
      protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException failed) throws IOException, ServletException {
      logger.info("Failed authentication while attempting to access");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed");
      }
      }


      Authorization class :-



      public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
      private static Logger logger = LoggerFactory.getLogger(JWTAuthorizationFilter.class);

      public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
      super(authenticationManager);
      }


      /**
      *
      * @param request
      * @param response
      * @param chain
      * @throws IOException
      * @throws ServletException
      */
      @Override
      protected void doFilterInternal(HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain) throws IOException, ServletException {
      logger.info("Entering doFilterInternal@JWTAuthorizationFilter");

      String header = request.getHeader(SecurityConstant.HEADER_STRING);
      logger.info("header:: {}", header);

      if(null == header || !header.startsWith(SecurityConstant.TOKEN_PREFIX)){
      logger.info("chaining");
      chain.doFilter(request, response);
      return;
      }

      UsernamePasswordAuthenticationToken authentication = getAuthentication(header);
      logger.info("Authentication:: {}", authentication);

      SecurityContextHolder.getContext().setAuthentication(authentication);
      chain.doFilter(request, response);

      }


      /**
      *
      * @param header
      * @return
      */
      private UsernamePasswordAuthenticationToken getAuthentication(String header){
      logger.info("Entering getAuthenticationToken@JWTAuthorizationFilter");
      logger.info("token::{}", header);
      if(null != header){

      //Parsing JWT Token
      String user = Jwts.parser()
      .setSigningKey(SecurityConstant.SECRET)
      .parseClaimsJws(header.replace(SecurityConstant.TOKEN_PREFIX, ""))
      .getBody()
      .getSubject();

      logger.info("user:: {}",user);
      if(null != user){
      return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
      }
      return null;
      }
      return null;
      }
      }


      WebSecurity class:-



      @EnableWebSecurity
      public class WebSecurity extends WebSecurityConfigurerAdapter {

      private UserDetailsService userDetailsService;

      private BCryptPasswordEncoder bCryptPasswordEncoder;


      public WebSecurity(UserDetailsService userDetailsService,
      BCryptPasswordEncoder bCryptPasswordEncoder) {
      this.userDetailsService = userDetailsService;
      this.bCryptPasswordEncoder = bCryptPasswordEncoder;
      }

      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
      }


      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http.cors().and().csrf()
      .disable()
      .authorizeRequests()
      .antMatchers(HttpMethod.POST, SecurityConstant.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);

      }

      @Bean
      CorsConfigurationSource corsConfigurationSource() {
      final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
      return source;
      }
      }


      Application.properties file:-



      #spring.security.user.name=user
      #spring.security.user.password=user

      spring.data.mongodb.uri=mongodb://localhost:27017/myspringdb


      PostMan test data for signup (it is working) :-



      http://localhost:8080/users/sign-up



      {
      "id":"2",
      "username":"user",
      "password":"user",
      "emailAddress":"abc@sample.com"
      }


      PostMan test data for sign-in (not working):-



      http://localhost:8080/login



      Header: content-type:application/json



      {
      "username":"user",
      "password":"user"
      }


      And also wants to know whether Im doing correct here not by using spring-security because while running the program, the program generates a password by itself like below :-



      Using generated security password: ki908a3f-00ec-98cc-bn02-823ead10f153



      Should I using my own credentials which saved in database (mongodb) or this spring generated password for authentication purpose?



      Thank you







      java rest spring-boot authentication jwt






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 6:51









      Chirdeep Tomar

      1,13021645




      1,13021645










      asked Nov 13 '18 at 6:18









      vinod827

      62




      62
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53274932%2funable-to-login-using-jwt-authentication-mechanism%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53274932%2funable-to-login-using-jwt-authentication-mechanism%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          List item for chat from Array inside array React Native

          Thiostrepton

          Caerphilly