Example usage for org.apache.shiro SecurityUtils getSubject

List of usage examples for org.apache.shiro SecurityUtils getSubject

Introduction

In this page you can find the example usage for org.apache.shiro SecurityUtils getSubject.

Prototype

public static Subject getSubject() 

Source Link

Document

Returns the currently accessible Subject available to the calling code depending on runtime environment.

Usage

From source file:br.com.criativasoft.opendevice.middleware.persistence.TransactionFilter.java

License:Open Source License

@Override
public ContainerRequest filter(ContainerRequest request) {

    // Ignore Web Resources.
    String path = request.getPath();
    if (WebUtils.isWebResource(path)) {
        return request;
    }//from  ww  w .j  ava  2  s.co  m

    Subject subject = SecurityUtils.getSubject();
    log.debug(
            "(" + request.getMethod() + ") " + request.getPath() + ", Auth(" + subject.isAuthenticated() + ")");

    EntityManager em = emf.createEntityManager();

    request.getProperties().put(KEY, em);

    HibernateProvider.setInstance(em);

    EntityTransaction tx = em.getTransaction();

    tx.begin();

    return request;
}

From source file:br.com.criativasoft.opendevice.restapi.resources.AccountRest.java

License:Open Source License

private Subject getSubject() {
    return SecurityUtils.getSubject();
}

From source file:br.com.criativasoft.opendevice.wsrest.filter.AuthenticationFilter.java

License:Open Source License

@Override
public ContainerRequest filter(ContainerRequest request) {

    // Ignore Web Resources.
    String path = request.getPath();
    if (WebUtils.isWebResource(path)) {
        return request;
    }//from ww  w  .j a  va  2s . c  o m

    Subject subject = SecurityUtils.getSubject();

    Session session = subject.getSession(false);

    if (session != null && subject.isAuthenticated()) {
        session.touch();
        return request;
    }

    if (!subject.isAuthenticated()) {

        // Google OAuth ( Ex.: Alexa Skill )
        String authorizationHeader = request.getHeaderValue(HttpHeaders.AUTHORIZATION);

        if (authorizationHeader != null && authorizationHeader.startsWith("Google")) {
            String token = authorizationHeader.substring("Google".length()).trim(); // Token

            GoogleAuthToken bearerToken = new GoogleAuthToken(token);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }

        }

        // Extract the token from the HTTP Authorization header (OAuth2)
        authorizationHeader = request.getHeaderValue(HttpHeaders.AUTHORIZATION);
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
            String token = authorizationHeader.substring("Bearer".length()).trim(); // API_KEY

            BearerAuthToken bearerToken = new BearerAuthToken(token);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // ApiKey in Header (no 2 step auth)
        String header = request.getHeaderValue("ApiKey");
        if ((authorizationHeader != null && authorizationHeader.startsWith("ApiKey")) || header != null) {
            String apiKey = null;
            if (header != null) {
                apiKey = header;
            } else {
                apiKey = authorizationHeader.substring("ApiKey".length()).trim(); // API_KEY
            }

            if (StringUtils.isEmpty(apiKey)) {
                log.warn("ApiKey not found in Request");
                throw new AuthenticationException("ApiKey Required");
            }

            BearerAuthToken bearerToken = new BearerAuthToken(apiKey, true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // WebSocket HttpHeader Upgrade (JavaScript Library).
        header = request.getHeaderValue("Upgrade");
        if (header != null && header.contains("websocket")) {

            String apiKey = path.substring(path.lastIndexOf('/') + 1, path.length());

            BearerAuthToken bearerToken = new BearerAuthToken(apiKey, true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // Query Param (in URL)

        MultivaluedMap<String, String> queryParameters = request.getQueryParameters();

        List<String> apiKeyParams = queryParameters.get("ApiKey");

        if (apiKeyParams != null) {

            BearerAuthToken bearerToken = new BearerAuthToken(apiKeyParams.get(0), true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // GoogleAssistant / Dialogflow Integration
        header = request.getHeaderValue("GoogleAssistant");
        if (header != null && header.contains("Dialogflow")) {

            JsonNode entity = request.getEntity(JsonNode.class);
            JsonNode userNode = entity.get("originalDetectIntentRequest").get("payload").get("user");

            if (userNode == null) {
                log.warn("User not found in Request");
                throw new AuthenticationException("Invalid User / Token");
            }
            String token = userNode.get("accessToken").asText();

            BearerAuthToken bearerToken = new BearerAuthToken(token);

            // request.setEntityInputStream(new ByteArrayInputStream(entity.toString().getBytes()));
            request.setEntityInputStream(new ByteArrayInputStream(entity.toString().getBytes()));
            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }
    }

    // NOTE: if not Autenticated, the UnauthenticatedException will throw (AuthorizationExceptionMap)

    return request;
}

From source file:br.com.criativasoft.opendevice.wsrest.filter.TenantFilter.java

License:Open Source License

@Override
public ContainerRequest filter(ContainerRequest request) {

    // Ignore Web Resources.
    String path = request.getPath();
    if (WebUtils.isWebResource(path)) {
        return request;
    }//from w  w  w . j  a  va 2 s.  c  om

    if (config.isAuthRequired()) {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession(false);

        if (subject.isAuthenticated()) {
            AccountPrincipal principal = (AccountPrincipal) subject.getPrincipal(); // return UUID from Account
            TenantProvider.setCurrentID(principal.getAccountUUID());
        } else {
            TenantProvider.setCurrentID(null);
        }
    }

    return request;
}

From source file:br.com.criativasoft.opendevice.wsrest.resource.OAuthRest.java

License:Open Source License

@GET
@Path("/authorize")
public Response authorize(@Context HttpServletRequest request) throws URISyntaxException, OAuthSystemException {

    Subject subject = SecurityUtils.getSubject();

    // Save request and go to login page
    if (!subject.isAuthenticated()) {
        WebUtils.saveRequest(request);/*from w w  w.  j a v  a  2 s  .co m*/
        URI uri = UriBuilder.fromUri("/login").build();
        return Response.seeOther(uri).build();
    }

    OAuthAuthzRequest oauthRequest;

    OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

    try {
        oauthRequest = new OAuthAuthzRequest(request);

        // build response according to response_type
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);

        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);

        String authCode = oauthIssuerImpl.authorizationCode();

        if (responseType.equals(ResponseType.CODE.toString())) {
            builder.setCode(authCode);
        } else {
            throw new IllegalArgumentException("responseType not allowed = " + responseType);
        }

        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
        URI url = new URI(response.getLocationUri());

        // Store autentication code in Token cache to validade in next phase (method: tokenPost)
        DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
        Cache<Object, Object> cache = securityManager.getCacheManager()
                .getCache(AuthenticationFilter.TOKEN_CACHE);

        AccountPrincipal principal = (AccountPrincipal) subject.getPrincipal();
        cache.put(authCode, principal.getUserAccountID());

        return Response.status(response.getResponseStatus()).location(url).build();

    } catch (OAuthProblemException e) {

        final Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_FOUND);

        String redirectUri = e.getRedirectUri();

        if (OAuthUtils.isEmpty(redirectUri)) {
            throw new WebApplicationException(
                    responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
        }

        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();

        final URI location = new URI(response.getLocationUri());

        return responseBuilder.location(location).build();
    }
}

From source file:br.com.diego.midia.managedBean.Login.java

public void submit() throws IOException {
    try {/*  w  ww.  j  a  va  2  s .c o  m*/
        SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(Faces.getRequest());
        Faces.redirect(savedRequest != null ? savedRequest.getRequestUrl() : HOME_URL);
    } catch (AuthenticationException e) {
        Messages.addGlobalError("Unknown user, please try again");
        e.printStackTrace(); // TODO: logger.
    }
}

From source file:br.com.diego.midia.managedBean.LogoutMB.java

public void submit() throws IOException {
    SecurityUtils.getSubject().logout();
    Faces.invalidateSession();
    Faces.redirect(HOME_URL);
}

From source file:br.com.diego.shiro.Login.java

public void submit() throws IOException {
    try {/*www  .j  av a2s  .co m*/
        SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(Faces.getRequest());
        Faces.redirect(savedRequest != null ? savedRequest.getRequestUrl() : HOME_URL);
    } catch (AuthenticationException e) {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        Messages.addGlobalError("Unknown user, please try again");
        e.printStackTrace(); // TODO: logger.
    }
}

From source file:br.com.diego.shiro.ShiroSecuredInterceptor.java

@AroundInvoke
public Object interceptShiroSecurity(InvocationContext context) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    Class<?> c = context.getTarget().getClass();
    Method m = context.getMethod();

    if (!subject.isAuthenticated() && hasAnnotation(c, m, RequiresAuthentication.class)) {
        throw new UnauthenticatedException("Authentication required");
    }/* ww w .jav a  2s  .c  o  m*/

    if (subject.getPrincipal() != null && hasAnnotation(c, m, RequiresGuest.class)) {
        throw new UnauthenticatedException("Guest required");
    }

    if (subject.getPrincipal() == null && hasAnnotation(c, m, RequiresUser.class)) {
        throw new UnauthenticatedException("User required");
    }

    RequiresRoles roles = getAnnotation(c, m, RequiresRoles.class);

    if (roles != null) {
        subject.checkRoles(Arrays.asList(roles.value()));
    }

    RequiresPermissions permissions = getAnnotation(c, m, RequiresPermissions.class);

    if (permissions != null) {
        subject.checkPermissions(permissions.value());
    }

    return context.proceed();
}

From source file:br.com.diego.shiro.SomeBean.java

public void doSomethingWhichIsOnlyAllowedByADMIN() {
    SecurityUtils.getSubject().checkRole("ADMIN");

}