1

I am trying to implement authentication and authorization using angular and java where I came across "identifying the current user asking for resource" from this Link

The point where I am not able to understand is getting the user from getUserPrincipal() method using jax-rs SecurityContext.

Security Context:

requestContext.setSecurityContext(new SecurityContext() {

    @Override
    public Principal getUserPrincipal() {

        return new Principal() {

            @Override
            public String getName() {
                return email;
            }
        };
    }
}

The above method apparently returns a user but the question is from where? I have searched on this topic but no where I see code for fetching the user from DB or any other resource.

Where as I have implemented some thing like this for validation:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the HTTP Authorization header from the request
        String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Check if the HTTP Authorization header is present and formatted correctly 
        if (authorizationHeader == null || !authorizationHeader.startsWith("Basic ")) {
            throw new NotAuthorizedException("Authorization header must be provided");
        }

        // Extract the token and email address from the HTTP Authorization header
        String email = requestContext.getHeaderString("Email");
        String token = authorizationHeader.substring("Basic".length()).trim();

        try {
            // Validate the token
            validateToken(email, token);

        } catch (Exception e) {
            requestContext.abortWith(
                    Response.status(Response.Status.UNAUTHORIZED).build());
        }

    private void validateToken(String email, String token) throws Exception {
        // Check if it was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
        try {
            TokenSaverAndValidatorDAO tokenValidator = new TokenSaverAndValidatorDAO();
            String result = tokenValidator.checkTokenFromDB(email, token);
            if (result.equals(token)) {
                System.out.println("Token is same");
            } else {
                System.out.println("Token is not same");
                throw new Exception();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The above method validateToken() calls a method from DAO class for validation:

public String checkTokenFromDB(String email, String token) {
        String result = "";
        try {
            String query = "Select USR_TOKEN From TBL_USER where USR_PRIMARY_EMAIL= ? ";
            Connection con = DBConnection.getConnection();
            PreparedStatement statement = con.prepareStatement(query);
            statement.setString(1, email);
            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                result = rs.getString("USR_TOKEN");
            }

        } catch (Exception ex) {
            System.out.println("Error in TokenSaverDAO class");
            ex.printStackTrace();
        }
        return result;
    }

How do I use jax-rs securityContext in my application. Does it apply to my scenario?

I am sending the headers from angular like this:

$httpProvider.interceptors.push(['$q', '$location', '$localStorage', 'jwtHelper', function ($q, $location, $localStorage, jwtHelper) {
    return {
        'request': function (config) {
            config.headers = config.headers || {};
            if ($localStorage.token) {
                var decodeToken = jwtHelper.decodeToken($localStorage.token);
                config.headers.Email = decodeToken.email;
                config.headers.Authorization = 'Basic ' + $localStorage.token;
            }
            return config;
        },
        'responseError': function (response) {
            if (response.status === 401 || response.status === 403) {
                $location.path('/Login');
            }
            return $q.reject(response);
        }
    };
}]);

Where the headers are set like this:

config.headers.Email = decodeToken.email;
config.headers.Authorization = 'Basic ' + $localStorage.token;
Community
  • 1
  • 1
kittu
  • 6,662
  • 21
  • 91
  • 185

0 Answers0