List of usage examples for org.apache.shiro.subject Subject getSession
Session getSession(boolean create);
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 om*/ 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; }/*w ww .jav a2s . c o m*/ 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.AuthRest.java
License:Open Source License
@POST @Produces(MediaType.APPLICATION_JSON)/*w w w . j av a 2 s.c om*/ public Response loginForm(@Context AtmosphereResource res, @Auth Subject currentUser, @FormParam("username") String username, @FormParam("password") String password) { if (currentUser.isAuthenticated()) return noCache(Response.status(Status.OK).entity("{\"messages\":[\"Already logged\"]}")); Response response = doLogin(currentUser, username, password, false); if (currentUser.isAuthenticated()) { AccountPrincipal principal = (AccountPrincipal) currentUser.getPrincipal(); // Generate Cookie to indentify user on Shiro (see NewShiroInterceptor) Session session = currentUser.getSession(true); // this will force session creation javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(AuthRest.SESSION_ID, (String) session.getId()); cookie.setPath("/"); res.getResponse().addCookie(cookie); session.setTimeout((1000 * 60) * 30); // min // // Generate Cookie to indentify ApiKey/AuthToken // cookie = new javax.servlet.http.Cookie(TenantProvider.HTTP_HEADER_KEY, principal.getAccountUUID()); // (String) session.getId() // cookie.setPath("/"); // res.getResponse().addCookie(cookie); } return response; }
From source file:com.baomidou.kisso.web.interceptor.SSOShiroInterceptor.java
License:Apache License
/** * ???//from www .j a v a 2 s. c om * <p> * Controller ?? * </p> */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { SSOToken token = SSOHelper.attrToken(request); if (token == null) { return true; } /** * shiro ?? */ Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(false); if (session != null) { session.touch(); } /** * shiro ? */ if (!currentUser.isAuthenticated()) { currentUser.login(new SSOAuthToken(token)); logger.fine(" shiro login success. "); } /** * URL ??? */ if (SSOConfig.getInstance().isPermissionUri()) { String uri = request.getRequestURI(); if (uri == null || currentUser.isPermitted(uri)) { return true; } } /** * ??? */ HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); Permission pm = method.getAnnotation(Permission.class); if (pm != null) { if (pm.action() == Action.Skip) { /** * */ return true; } else if (!"".equals(pm.value()) && currentUser.isPermitted(pm.value())) { /** * ??? */ return true; } } /** * ?? */ return unauthorizedAccess(request, response); } return true; }
From source file:com.caricah.iotracah.bootstrap.security.IOTSecurityManager.java
License:Apache License
protected void stopSession(Subject subject) { Session s = subject.getSession(false); if (s != null) { s.stop(); } }
From source file:com.caricah.iotracah.bootstrap.security.realm.state.IOTSubject.java
License:Apache License
public void login(AuthenticationToken token) throws AuthenticationException { Subject subject = securityManager.login(this, token); PrincipalCollection principals;//from w w w . j a v a 2 s .c om IOTSubject iotSubject = (IOTSubject) subject; //we have to do this in case there are assumed identities - we don't want to lose the 'real' principals: principals = iotSubject.principals; String host = iotSubject.host; if (principals == null || principals.isEmpty()) { String msg = "Principals returned from securityManager.login( token ) returned a null or " + "empty value. This value must be non null and populated with one or more elements."; throw new IllegalStateException(msg); } this.principals = principals; this.authenticated = true; if (token instanceof HostAuthenticationToken) { host = ((HostAuthenticationToken) token).getHost(); } if (host != null) { this.host = host; } this.session = subject.getSession(false); }
From source file:com.caricah.iotracah.core.handlers.RequestHandler.java
License:Apache License
public Observable<IOTClient> checkPermission(String sessionId, String authKey, AuthorityRole role, List<String> topicList) { return Observable.create(observable -> { IotClientKey clientKey = new IotClientKey(); clientKey.setSessionId(sessionId); Subject subject = new Subject.Builder().sessionId(clientKey).buildSubject(); final IOTClient session = (IOTClient) subject.getSession(false); if (session != null && subject.isAuthenticated()) { try { if (!AuthorityRole.CONNECT.equals(role)) { if (Protocol.fromString(session.getProtocol()).isNotPersistent()) { String session_auth_key = session.getAuthKey(); /** * Make sure for non persistent connections the authKey matches * the stored authKey. Otherwise fail the request. *//*from w ww .j a v a2s .c o m*/ if (!StringUtils.isEmpty(session_auth_key)) { if (!session_auth_key.equals(authKey)) throw new UnauthenticatedException("Client fails auth key assertion."); } } List<Permission> permissions = topicList.stream() .map(topic -> getPermission(session.getPartitionId(), session.getUsername(), session.getClientIdentification(), role, topic)) .collect(Collectors.toList()); subject.checkPermissions(permissions); } //Update session last accessed time. session.touch(); observable.onNext(session); observable.onCompleted(); } catch (AuthorizationException e) { //Notify failure to authorize user. observable.onError(e); } } else { observable.onError(new AuthenticationException( "Client must be authenticated {Try connecting first} found : " + session)); } }); }
From source file:com.ddy.dianmai.ops.filter.OnlineSessionFilter.java
License:Apache License
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { System.out.println("OnlineSessionFilter-isAccessAllowed"); Subject subject = getSubject(request, response); if (subject == null || subject.getSession(false) == null) { return true; }/*from ww w . j a v a 2 s.co m*/ Session session = sessionDAO.readSession(subject.getSession().getId()); if (session != null && session instanceof OnlineSession) { OnlineSession onlineSession = (OnlineSession) session; request.setAttribute(Constants.ONLINE_SESSION, onlineSession); if (onlineSession.getStatus() == OnlineSession.OnlineStatus.force_logout) { return false; } } return true; }
From source file:com.funtl.framework.smoke.core.modules.sys.utils.UserUtils.java
License:Apache License
public static Session getSession() { try {// w ww . j a va 2 s .com Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session == null) { session = subject.getSession(); } if (session != null) { return session; } // subject.logout(); } catch (InvalidSessionException e) { } return null; }
From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java
License:Open Source License
@Override public String login(Credential credential) throws ServiceException { String login = credential.getUsername(); char[] password = credential.getPassword(); boolean rememberMe = credential.isRememberMe(); try {/*from w w w .ja va 2 s. c o m*/ if (log.isTraceEnabled()) { log.trace(String.format("login - %s", credential)); } UsernamePasswordToken token = new UsernamePasswordToken(login, password, rememberMe); AuthenticationInfo info = securityManager.authenticate(token); if (log.isTraceEnabled()) { if (info instanceof SimpleAuthenticationInfo) { PrincipalCollection principals = ((SimpleAuthenticationInfo) info).getPrincipals(); for (Object principal : principals.asList()) { log.trace("Principal: " + principal); } } } token.clear(); // Create subject for the current principal Subject subject = new Subject.Builder().principals(info.getPrincipals()).buildSubject(); // log.trace("subject.getPrincipal(): " + subject.getPrincipal()); // Create session org.apache.shiro.session.Session session = subject.getSession(true); if (session == null) { throw new ServiceException(String.format("Unable to create session for ", login)); } session.setAttribute(ES_DMS_LOGIN_ATTRIBUTE, login); session.setAttribute(ES_DMS_ID_ATTRIBUTE, ((User) subject.getPrincipal()).getId()); ThreadContext.bind(subject); // if (log.isTraceEnabled()) { // Subject currentUser = SecurityUtils.getSubject(); // log.trace("currentUser.getPrincipal(): " + // currentUser.getPrincipal()); // } return session.getId().toString(); } catch (AuthenticationException aEx) { String message = String.format("Authentication failed for %s", login); log.error(message, aEx); throw new ServiceException(message); } }