识别请求其余端点的当前用户

时间:2016-01-19 19:08:28

标签: java angularjs web-services rest jersey-2.0

我正在尝试使用angular和java实现身份验证和授权,我在这里找到了“识别当前用户要求资源”Link

我无法理解的一点是使用jax-rs SecurityContext从getUserPrincipal()方法获取用户。

安全背景:

requestContext.setSecurityContext(new SecurityContext() {

    @Override
    public Principal getUserPrincipal() {

        return new Principal() {

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

上面的方法显然会返回一个用户,但问题是从哪里来的?我已经搜索了这个主题,但没有看到从DB或任何其他资源中获取用户的代码。

我在哪里实施了这样的事情进行验证:

@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();
        }
    }
}

上述方法validateToken()从DAO类调用一个方法进行验证:

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;
    }

如何在我的应用程序中使用jax-rs securityContext。它适用于我的场景吗?

我正在从角度发送标题:

$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);
        }
    };
}]);

标题设置如下:

config.headers.Email = decodeToken.email;
config.headers.Authorization = 'Basic ' + $localStorage.token;

0 个答案:

没有答案