org.springframework.security.core.Authentication Java Examples

The following examples show how to use org.springframework.security.core.Authentication. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JwtAuthenticationTokenFilter.java    From sakai with Educational Community License v2.0 7 votes vote down vote up
/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

    String header = request.getHeader(tokenHeader);
    if (header == null || !header.startsWith("Bearer ")) {
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String authToken = header.substring(7);

    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        JwtAuthenticationToken authentication = new JwtAuthenticationToken(authToken);
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    return SecurityContextHolder.getContext().getAuthentication();
}
 
Example #2
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }
    CalendarUser user = (CalendarUser) authentication.getPrincipal();
    String email = user.getEmail();        if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }

    logger.info("CalendarUser: {}", result);
    return result;
}
 
Example #3
Source File: KerberosService.java    From nifi with Apache License 2.0 6 votes vote down vote up
public Authentication validateKerberosTicket(HttpServletRequest request) {
    // Only support Kerberos login when running securely
    if (!request.isSecure()) {
        return null;
    }

    String header = request.getHeader(AUTHORIZATION_HEADER_NAME);

    if (isValidKerberosHeader(header)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(header.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8);
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));

        return kerberosServiceAuthenticationProvider.authenticate(authenticationRequest);
    } else {
        return null;
    }
}
 
Example #4
Source File: DefaultJwtSecurityTokenService.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication createAuthentication(String token) throws BadCredentialsException {
	Claims claims = createClaimsFromToken(token);
	DateTime expireation = new DateTime(claims.getExpiration());
	if(expireation.isBeforeNow()){
		return null;
	}
	String authorityString = claims.get(JwtSecurityUtils.CLAIM_AUTHORITIES).toString();
	List<GrantedAuthority> authorities = GuavaUtils.splitAsStream(authorityString, ",").map(auth->{
		return new SimpleGrantedAuthority(auth);
	})
	.collect(Collectors.toList());
	
	Authentication authentication = buildAuthentication(claims, authorities);
	return authentication;
}
 
Example #5
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
 * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
 * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
 * application Spring Security usernames are email addresses).
 */
@Override
public CalendarUser getCurrentUser() {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return null;
    }
    CalendarUser user = (CalendarUser) authentication.getPrincipal();
    String email = user.getEmail();        if (email == null) {
        return null;
    }
    CalendarUser result = calendarService.findUserByEmail(email);
    if (result == null) {
        throw new IllegalStateException(
                "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
    }

    logger.info("CalendarUser: {}", result);
    return result;
}
 
Example #6
Source File: CustomAuthenticationProvider.java    From hauth-java with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    Object pd = authentication.getCredentials();
    if (pd == null) {
        return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>());
    }
    String password = pd.toString();
    UserLoginEntity userLoginEntity = loginService.loginValidator(name, password);
    // 认证逻辑
    if (userLoginEntity.isFlag()) {
        return getRole(name, password);
    } else {
        logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage());
        throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity));
    }
}
 
Example #7
Source File: AjaxLogoutSuccessHandler.java    From todo-spring-angular with MIT License 6 votes vote down vote up
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                            Authentication authentication)
    throws IOException, ServletException {

    // Request the token
    String token = request.getHeader("authorization");
    if (token != null && token.startsWith(BEARER_AUTHENTICATION)) {
        final OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(StringUtils.substringAfter(token, BEARER_AUTHENTICATION));

        if (oAuth2AccessToken != null) {
            tokenStore.removeAccessToken(oAuth2AccessToken);
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
}
 
Example #8
Source File: UserNamespaceAuthorizationServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateUserNamespaceAuthorizationLowerCaseParameters()
{
    // Override the security context to return an application user populated with test values.
    Authentication originalAuthentication = overrideSecurityContext();

    // Create a user namespace authorization key.
    UserNamespaceAuthorizationKey key = new UserNamespaceAuthorizationKey(USER_ID, NAMESPACE);

    // Create and persist the relative database entities.
    UserNamespaceAuthorizationEntity userNamespaceAuthorizationEntity = userNamespaceAuthorizationDaoTestHelper
        .createUserNamespaceAuthorizationEntity(key, Arrays.asList(NamespacePermissionEnum.READ, NamespacePermissionEnum.WRITE));

    // Update a user namespace authorization using lowercase input parameters.
    UserNamespaceAuthorization resultUserNamespaceAuthorization = userNamespaceAuthorizationService
        .updateUserNamespaceAuthorization(new UserNamespaceAuthorizationKey(key.getUserId().toLowerCase(), key.getNamespace().toLowerCase()),
            new UserNamespaceAuthorizationUpdateRequest(SUPPORTED_NAMESPACE_PERMISSIONS));

    // Validate the returned object.
    assertEquals(new UserNamespaceAuthorization(userNamespaceAuthorizationEntity.getId(), key, SUPPORTED_NAMESPACE_PERMISSIONS),
        resultUserNamespaceAuthorization);

    // Restore the original authentication.
    restoreSecurityContext(originalAuthentication);
}
 
Example #9
Source File: ReservationApiV2Controller.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
private ResponseEntity<Void> handleReservationWith(String eventName, String reservationId, Authentication authentication,
                                                   BiFunction<Event, TicketReservation, ResponseEntity<Void>> with) {
    ResponseEntity<Void> notFound = ResponseEntity.notFound().build();
    ResponseEntity<Void> badRequest = ResponseEntity.badRequest().build();



    return eventRepository.findOptionalByShortName(eventName).map(event -> {
            if(canAccessReceiptOrInvoice(event, authentication)) {
                return ticketReservationManager.findById(reservationId).map(ticketReservation -> with.apply(event, ticketReservation)).orElse(notFound);
            } else {
                return badRequest;
            }
        }
    ).orElse(notFound);
}
 
Example #10
Source File: _CustomPersistentRememberMeServices.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * When logout occurs, only invalidate the current token, and not all user sessions.
 * <p>
 * The standard Spring Security implementations are too basic: they invalidate all tokens for the
 * current user, so when he logs out from one browser, all his other sessions are destroyed.
 */
@Override
@Transactional
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String rememberMeCookie = extractRememberMeCookie(request);
    if (rememberMeCookie != null && rememberMeCookie.length() != 0) {
        try {
            String[] cookieTokens = decodeCookie(rememberMeCookie);
            PersistentToken token = getPersistentToken(cookieTokens);
            persistentTokenRepository.delete(token);
        } catch (InvalidCookieException ice) {
            log.info("Invalid cookie, no persistent token could be deleted");
        } catch (RememberMeAuthenticationException rmae) {
            log.debug("No persistent token found, so no token could be deleted");
        }
    }
    super.logout(request, response, authentication);
}
 
Example #11
Source File: KeycloakAuthenticationFilter.java    From camunda-bpm-identity-keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {

       // Get the Bearer Token and extract claims
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
       String accessToken = details.getTokenValue();
       String claims = JwtHelper.decode(accessToken).getClaims();
       
       // Extract user ID from Token claims -depending on Keycloak Identity Provider configuration
       // String userId = Spin.JSON(claims).prop("sub").stringValue();
       String userId = Spin.JSON(claims).prop("email").stringValue(); // useEmailAsCamundaUserId = true
       // String userId = Spin.JSON(claims).prop("preferred_username").stringValue(); // useUsernameAsCamundaUserId = true
       LOG.debug("Extracted userId from bearer token: {}", userId);

       try {
       	identityService.setAuthentication(userId, getUserGroups(userId));
       	chain.doFilter(request, response);
       } finally {
       	identityService.clearAuthentication();
       }
}
 
Example #12
Source File: CalendarUserAuthenticationProvider.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
 
Example #13
Source File: DbAuthModule.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getName(String token, String user) throws PrincipalAdapterException {
	String name = null;
	Authentication oldAuth = null;

	try {
		if (token == null) {
			PrincipalUtils.getAuthentication();
		} else {
			oldAuth = PrincipalUtils.getAuthentication();
			PrincipalUtils.getAuthenticationByToken(token);
		}

		name = CommonAuthModule.getName(user);
	} catch (AccessDeniedException e) {
		throw new PrincipalAdapterException(e.getMessage(), e);
	} finally {
		if (token != null) {
			PrincipalUtils.setAuthentication(oldAuth);
		}
	}

	return name;
}
 
Example #14
Source File: CustomAuthenticationProvider.java    From batch-scheduler with MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    Object pd = authentication.getCredentials();
    if (pd == null) {
        return new UsernamePasswordAuthenticationToken(name, "", new ArrayList<>());
    }
    String password = pd.toString();
    UserLoginEntity userLoginEntity = loginService.loginValidator(name, password);
    // 认证逻辑
    if (userLoginEntity.isFlag()) {
        return getRole(name, password);
    } else {
        logger.info("登录失败,原因是:账号 {}: {}", userLoginEntity.getUsername(), userLoginEntity.getMessage());
        throw new BadCredentialsException(new GsonBuilder().create().toJson(userLoginEntity));
    }
}
 
Example #15
Source File: RemoteIdmAuthenticationProvider.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RemoteUser user = remoteIdmService.authenticateUser(authentication.getPrincipal().toString(), authentication.getCredentials().toString());
    if (user == null) {
        throw new FlowableException("user not found " + authentication.getPrincipal());
    }

    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    for (String privilege : user.getPrivileges()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
    }

    Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials(), grantedAuthorities);
    return auth;
}
 
Example #16
Source File: CfpControllerTest.java    From spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@WithMockUser("jsmith")
@Test
public void submitTalk() throws Exception {
	Authentication authentication = new TestingAuthenticationToken(
			new User("jsmith", "John Smith"), "secret", "ROLE_USER");

	given(this.submissionService.create(any())).willReturn(new Submission());
	this.mvc.perform(post("/submit")
			.param("title", "Alice in Wonderland")
			.param("summary", "my abstract")
			.param("track", Track.ALTERNATE_LANGUAGES.getId())
			.param("notes", "this rocks")
			.with(authentication(authentication))
			.with(csrf()))
			.andExpect(status().isFound())
			.andExpect(header().string(HttpHeaders.LOCATION, "/submit?navSection=submit"));
	verify(this.submissionService).create(any());
}
 
Example #17
Source File: MyAccessDecisionManager.java    From demo-project with MIT License 6 votes vote down vote up
@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
	    //无需验证放行
	    if(configAttributes==null || configAttributes.size()==0)
	        return;
	    log.info("开始验证");
//	    if(!authentication.isAuthenticated()){
        if(authenticationTrustResolver.isAnonymous(authentication)){
	        throw new InsufficientAuthenticationException("未登录");
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for(ConfigAttribute attribute : configAttributes){
            if(!(attribute instanceof MyConfigAttribute)) continue;
            MyConfigAttribute urlConfigAttribute = (MyConfigAttribute)attribute;
            for(GrantedAuthority authority: authorities){
                if(!(authority instanceof MyGrantedAuthority)) continue;
                MyGrantedAuthority myGrantedAuthority = (MyGrantedAuthority)authority;
                if(urlConfigAttribute.getMyGrantedAuthority().equals(myGrantedAuthority))
                    return;
            }
        }
        throw new AccessDeniedException("无权限");
	}
 
Example #18
Source File: MyAccessDecisionManager.java    From maintain with MIT License 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object obj, Collection<ConfigAttribute> configAttributes)
		throws AccessDeniedException, InsufficientAuthenticationException {
	if (null == configAttributes || configAttributes.size() <= 0) {
		logger.info("decide == return");
		return;
	}
	ConfigAttribute c;
	String needRole;
	for (Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext();) {
		c = iter.next();
		needRole = c.getAttribute();
		logger.info("need======" + needRole.trim() + "  size=" + authentication.getAuthorities());
		for (GrantedAuthority ga : authentication.getAuthorities()) {
			logger.info("needRole==" + needRole.trim() + " [] = authority=" + ga.getAuthority());
			// authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合
			if (needRole.trim().equals(ga.getAuthority())) {
				return;
			}
		}
	}
	throw new AccessDeniedException("no right");
}
 
Example #19
Source File: DominiController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response getTipoPendenza(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, String idTipoPendenza) {
	String methodName = "getTipoPendenza";  
	String transactionId = ContextThreadLocal.get().getTransactionId();
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
	try{
		// autorizzazione sulla API
		this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.OPERATORE, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.ANAGRAFICA_CREDITORE), Arrays.asList(Diritti.LETTURA));

		ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
		validatoreId.validaIdDominio("idDominio", idDominio);
		validatoreId.validaIdTipoVersamento("idTipoPendenza", idTipoPendenza);

		// Parametri - > DTO Input

		GetTipoPendenzaDominioDTO getTipoPendenzaDominioDTO = new GetTipoPendenzaDominioDTO(user, idDominio, idTipoPendenza);

		// INIT DAO

		DominiDAO dominiDAO = new DominiDAO(false);

		// CHIAMATA AL DAO

		GetTipoPendenzaDominioDTOResponse getTipoPendenzaDominioDTOResponse = dominiDAO.getTipoPendenza(getTipoPendenzaDominioDTO); 

		// CONVERT TO JSON DELLA RISPOSTA

		TipoPendenzaDominio response = DominiConverter.toTipoPendenzaRsModel(getTipoPendenzaDominioDTOResponse);

		this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
		return this.handleResponseOk(Response.status(Status.OK).entity(response.toJSON(null)),transactionId).build();

	}catch (Exception e) {
		return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
	} finally {
		this.log(ContextThreadLocal.get());
	}
}
 
Example #20
Source File: SpringSecurityAuditorAware.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Override
public String getCurrentAuditor() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return "FULLSTOP";
    } else {
        final String userName = authentication.getName();
        logger.trace("Found Auditor: {}", userName);

        Assert.hasText(userName, "Username should never by empty");

        return userName;
    }
}
 
Example #21
Source File: MultiDeviceRememberMeServices.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    super.logout(request, response, authentication);

    if (authentication != null) {
        val username = authentication.getName();
        val userAgent = getUserAgent(request);
        tokenRepository.removeUserTokens(username, userAgent);
    }
}
 
Example #22
Source File: UserController.java    From tutorials with MIT License 5 votes vote down vote up
@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value = "/user")
public String user(Model model, Principal principal) {
    UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
    model.addAttribute("username", currentUser.getUsername());
    return "user";
}
 
Example #23
Source File: BaseController.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String getAuthenticatedUserName() throws Exception{
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if(authentication != null){
		return authentication.getName();
	}else{
		throw new Exception("No user logged in ");
	}
}
 
Example #24
Source File: DbRepositoryModule.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Folder getPersonalFolder(String token) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException {
	log.debug("getPersonalFolder({})", token);
	Folder personalFolder = new Folder();
	Authentication auth = null, oldAuth = null;

	try {
		if (token == null) {
			auth = PrincipalUtils.getAuthentication();
		} else {
			oldAuth = PrincipalUtils.getAuthentication();
			auth = PrincipalUtils.getAuthenticationByToken(token);
		}

		String personalPath = "/" + Repository.PERSONAL + "/" + auth.getName();
		String personalUuid = NodeBaseDAO.getInstance().getUuidFromPath(personalPath);
		NodeFolder personalNode = NodeFolderDAO.getInstance().findByPk(personalUuid);
		personalFolder = BaseFolderModule.getProperties(auth.getName(), personalNode);

		// Activity log
		UserActivity.log(auth.getName(), "GET_PERSONAL_FOLDER", personalNode.getUuid(), personalPath, null);
	} catch (DatabaseException e) {
		throw e;
	} finally {
		if (token != null) {
			PrincipalUtils.setAuthentication(oldAuth);
		}
	}

	log.debug("getPersonalFolder: {}", personalFolder);
	return personalFolder;
}
 
Example #25
Source File: CalendarUserAuthenticationProvider.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    String password = user.getPassword();
    if(!password.equals(token.getCredentials())) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
 
Example #26
Source File: Oauth2Service.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
public String getUserPrincipal(){
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userPrincipal = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userPrincipal = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userPrincipal = (String) authentication.getPrincipal();
        }
    }
    return userPrincipal;
}
 
Example #27
Source File: TokenAuthService.java    From egeria with Apache License 2.0 5 votes vote down vote up
public Authentication getAuthentication(HttpServletRequest request) {
    final String token = request.getHeader(AUTH_HEADER_NAME);
    if (token != null && !token.isEmpty()) {
        final TokenUser user = parseUserFromToken(token, secret);
        if (user != null) {
            return new UserAuthentication(user);
        }
    }
    return null;
}
 
Example #28
Source File: OAuth2Controller.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 移除access_token和refresh_token
 * 
 * @param access_token
 */
@ApiOperation(value = "移除token")
@PostMapping(value = "/oauth/remove/token", params = "access_token")
public void removeToken(String access_token) {

	// 拿到当前用户信息
	Authentication user = SecurityContextHolder.getContext().getAuthentication();

	if (user != null) {
		if (user instanceof OAuth2Authentication) {
			Authentication athentication = (Authentication) user;
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails();
		}

	}
	OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token);
	if (accessToken != null) {
		// 移除access_token
		tokenStore.removeAccessToken(accessToken);

		// 移除refresh_token
		if (accessToken.getRefreshToken() != null) {
			tokenStore.removeRefreshToken(accessToken.getRefreshToken());
		}

	}
}
 
Example #29
Source File: GitHubAuthFilter.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Handles an authentication request.
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
	final String requestURI = request.getRequestURI();
	UserAuthentication userAuth = null;

	if (requestURI.endsWith(GITHUB_ACTION)) {
		String authCode = request.getParameter("code");
		if (!StringUtils.isBlank(authCode)) {
			String appid = SecurityUtils.getAppidFromAuthRequest(request);
			String redirectURI = SecurityUtils.getRedirectUrl(request);
			App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
			String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.GITHUB_PREFIX);
			String entity = Utils.formatMessage(PAYLOAD, authCode, Utils.urlEncode(redirectURI), keys[0], keys[1]);

			HttpPost tokenPost = new HttpPost(TOKEN_URL);
			tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
			tokenPost.setHeader(HttpHeaders.ACCEPT, "application/json");
			tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
			try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
				if (resp1 != null && resp1.getEntity() != null) {
					Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
					if (token != null && token.containsKey("access_token")) {
						userAuth = getOrCreateUser(app, (String) token.get("access_token"));
					}
					EntityUtils.consumeQuietly(resp1.getEntity());
				}
			}
		}
	}

	return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
}
 
Example #30
Source File: TokenProviderTest.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@Test
public void testReturnFalseWhenJWTisMalformed() {
    Authentication authentication = createAuthentication();
    String token = tokenProvider.createToken(authentication, false);
    String invalidToken = token.substring(1);
    boolean isTokenValid = tokenProvider.validateToken(invalidToken);

    assertThat(isTokenValid).isEqualTo(false);
}