Skip to content
Advertisement

Azure AD with spring boot with user in local Database

Helo Here, I Hope you are doing well. I’s been few days I’m having this problem.

I have a spring boot API using Azure AD authentication thanks to AADResourceServerWebSecurityConfigurerAdapter.

Here is the flow I want to have:

  1. User gets token from Azure in the react native frontend (done)
  2. User logs into the api thanks to the given token. (to-do)
  3. If user doesn’t exists in local db, then it’s created thanks to info from the token.

Here is my question: How can I do to be able to have a callback / function executed when the user first connect to the api with a new token ? With this answer, I will be able to check if an user exist with the provided email in the token, and create it if it’s not existing.

Here is my websecurity config:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AADOAuth2ResourceServerSecurityConfig extends AADResourceServerWebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs"
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests().antMatchers("*").permitAll();
       http.cors().and().csrf().disable();
//       super.configure(http);
    }
}

I know this is messy because it is stil a part in development, but I would like to complete it thank to your information.

Thanks, Alex

Advertisement

Answer

As you said that you’ve done the step of getting access token. So I think you can add a filter to judge if the user contained in the token exists in your database. Here’s a sample filter.

package com.example.demo;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

//@Component
@WebFilter(filterName = "JwtRequestFilter", urlPatterns = {"/helloworld/*"})
public class JwtRequestFilter extends OncePerRequestFilter {
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        final String requestTokenHeader = request.getHeader("Authorization");

        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
            jwtToken = requestTokenHeader.substring(7);
            try {
                DecodedJWT jwt = JWT.decode(jwtToken);
                //set the claim name in the parameter to obtain email address
                String email = jwt.getClaim("unique_name").asString();
                //use email address to check if it exists in database
                Date expiresAt = jwt.getExpiresAt();
                if(expiresAt.before(new Date())) {
                    Map<String, Object> errRes = new HashMap<String, Object>();
                    Map<String, Object> errMesg = new HashMap<String, Object>();
                    errMesg.put("code", "InvalidAuthenticationToken");
                    errMesg.put("message", "Access token has expired.");
                    errRes.put("error", errMesg);
                    String json = JSONObject.toJSONString(errRes);   
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, json);
                    return;
                }
            } catch (JWTDecodeException exception){
                System.out.println("Unable to Decode the JWT Token");
            }
        } else {
            logger.warn("JWT Token does not begin with Bearer String");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        filterChain.doFilter(request, response);
    }

}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement