org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken Java Examples

The following examples show how to use org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken. 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: UserUtils.java    From syhthems-platform with MIT License 8 votes vote down vote up
/**
 * 从 Spring Security Context中获取 username 再获取 CustomUserDetails,若找不到则返回 null
 *
 * @return
 */
public CustomUserDetails getCustomUserDetailsFromSecurityContextHolderWithUsername() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        return null;
    }
    String username;
    if (authentication instanceof JwtAuthenticationToken) {
        username = ((JwtAuthenticationToken) authentication).getTokenAttributes().get("user_name").toString();
    } else {
        username = authentication.getName();
    }
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails instanceof CustomUserDetails) {
            return ((CustomUserDetails) userDetails).erasePassword();
        }
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    }
}
 
Example #2
Source File: AbstractFlowController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
protected ServiceCallResponse fromServiceB(JwtAuthenticationToken jwtAuthentication,
											HttpServletRequest request,
											ServiceCallResponse... serviceCallResponses) {

	ServiceCallResponse serviceCallResponse = new ServiceCallResponse();
	serviceCallResponse.setServiceName(SERVICE_B);
	serviceCallResponse.setServiceUri(request.getRequestURL().toString());
	serviceCallResponse.setJti(jwtAuthentication.getToken().getId());
	serviceCallResponse.setSub(jwtAuthentication.getToken().getSubject());
	serviceCallResponse.setAud(jwtAuthentication.getToken().getAudience());
	serviceCallResponse.setAuthorities(jwtAuthentication.getAuthorities().stream()
			.map(GrantedAuthority::getAuthority).sorted().collect(Collectors.toList()));
	if (serviceCallResponses != null) {
		serviceCallResponse.setServiceCallResponses(Arrays.asList(serviceCallResponses));
	}

	return serviceCallResponse;
}
 
Example #3
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #4
Source File: UserUtils.java    From syhthems-platform with MIT License 5 votes vote down vote up
/**
 * 得到当前用户的用户名
 *
 * @return username or null
 */
public static String getUsername() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        return null;
    } else if (authentication instanceof JwtAuthenticationToken) {
        return ((JwtAuthenticationToken) authentication).getTokenAttributes().get("user_name").toString();
    } else {
        return authentication.getName();
    }
}
 
Example #5
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #6
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #7
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #8
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #9
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #10
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #11
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #12
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #13
Source File: TestController.java    From oauth2-resource with MIT License 5 votes vote down vote up
@ApiOperation(value = "测试接口-优惠券列表")
@GetMapping("/coupon/list")
public Map<String, Object> couponList(JwtAuthenticationToken authenticationToken) {
    Map<String, Object> result = new HashMap<>(16);
    result.put("status", 1);
    result.put("data", couponService.list(authenticationToken.getToken().getSubject()));
    return result;
}
 
Example #14
Source File: TestController.java    From oauth2-resource with MIT License 5 votes vote down vote up
@ApiOperation("测试接口-产品列表")
@GetMapping("/product/list")
public Map<String, Object> productList(JwtAuthenticationToken authenticationToken) {
    Map<String, Object> result = new HashMap<>(16);
    result.put("status", 1);
    result.put("data", new ArrayList<>());
    return result;
}
 
Example #15
Source File: TestController.java    From oauth2-resource with MIT License 5 votes vote down vote up
@ApiOperation("测试接口-订单列表列表")
@GetMapping("/order/list")
public Map<String, Object> orderList(JwtAuthenticationToken authenticationToken) {
    Map<String, Object> result = new HashMap<>(16);
    result.put("status", 1);
    result.put("data", new ArrayList<>());
    return result;
}
 
Example #16
Source File: Swagger2Configuration.java    From oauth2-resource with MIT License 5 votes vote down vote up
@Bean
    public Docket createRestApi() {
        ParameterBuilder aParameterBuilder = new ParameterBuilder();
        aParameterBuilder
            .name("Authorization")
            .description("Authorization")
            .modelRef(new ModelRef("string"))
            .parameterType("header")
            .description("Bearer授权模式,'Bearer '开始")
            .required(false)
            .build()
        ;

        List<Parameter> aParameters = new ArrayList<>();
        aParameters.add(aParameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(Principal.class)
            .ignoredParameterTypes(JwtAuthenticationToken.class)
//            .globalOperationParameters(aParameters)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.revengemission.sso.oauth2.resource.coupon.controller"))
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(securitySchemes())
            .securityContexts(securityContexts());
    }
 
Example #17
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof JwtAuthenticationToken) {
        final String defaultTenant = "DEFAULT";

        final JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
        final Jwt jwt = jwtAuthenticationToken.getToken();
        final OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(),
                jwt.getClaims());
        final OidcUserInfo userInfo = new OidcUserInfo(jwt.getClaims());

        final Set<GrantedAuthority> authorities = authoritiesExtractor.extract(clientRegistration.getClientId(),
                jwt.getClaims());

        if (authorities.isEmpty()) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        final DefaultOidcUser user = new DefaultOidcUser(authorities, idToken, userInfo);

        final OAuth2AuthenticationToken oAuth2AuthenticationToken = new OAuth2AuthenticationToken(user, authorities,
                clientRegistration.getRegistrationId());

        oAuth2AuthenticationToken.setDetails(new TenantAwareAuthenticationDetails(defaultTenant, false));

        systemSecurityContext.runAsSystemAsTenant(systemManagement::getTenantMetadata, defaultTenant);
        SecurityContextHolder.getContext().setAuthentication(oAuth2AuthenticationToken);
    }

    chain.doFilter(request, response);
}
 
Example #18
Source File: WebClientConfig.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper() {
	return authorizeRequest -> {
		Map<String, Object> contextAttributes = Collections.emptyMap();
		if (authorizeRequest.getPrincipal() instanceof JwtAuthenticationToken) {
			contextAttributes = new HashMap<>();
			contextAttributes.put(JwtBearerOAuth2AuthorizedClientProvider.JWT_ATTRIBUTE_NAME,
					((JwtAuthenticationToken) authorizeRequest.getPrincipal()).getToken());
		}
		return contextAttributes;
	};
}
 
Example #19
Source File: HomeController.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@GetMapping("/home")
public String howdy(Principal principal) {
    String username = principal.getName();
    JwtAuthenticationToken token = (JwtAuthenticationToken) principal;
    log.info("claims: " + token.getTokenAttributes());
    return "Hello, " + username;
}
 
Example #20
Source File: MessagesController.java    From messaging-app with Apache License 2.0 5 votes vote down vote up
@GetMapping("/inbox")
public Iterable<Message> inbox(@AuthenticationPrincipal JwtAuthenticationToken token) {
	Collection<Message> messages = this.messageRepository.getInbox();
	if (hasAuthority(token, CONTACTS_AUTHORITY)) {
		return messages.stream()
				.map(this::addUserInformation)
				.collect(Collectors.toList());
	}
	return messages;
}
 
Example #21
Source File: MessagesController.java    From messaging-app with Apache License 2.0 5 votes vote down vote up
@GetMapping("/sent")
public Iterable<Message> sent(@AuthenticationPrincipal JwtAuthenticationToken token) {
	Collection<Message> messages = this.messageRepository.getSent();
	if (hasAuthority(token, CONTACTS_AUTHORITY)) {
		return messages.stream()
				.map(this::addUserInformation)
				.collect(Collectors.toList());
	}
	return messages;
}
 
Example #22
Source File: MessagesController.java    From messaging-app with Apache License 2.0 5 votes vote down vote up
@GetMapping("/{id}")
public Message get(@AuthenticationPrincipal JwtAuthenticationToken token,
					@PathVariable Long id) {
	Message message = this.messageRepository.findById(id).orElse(null);
	if (hasAuthority(token, CONTACTS_AUTHORITY)) {
		return addUserInformation(message);
	}
	return message;
}
 
Example #23
Source File: MessagesController.java    From messaging-app with Apache License 2.0 5 votes vote down vote up
@PostMapping
public Message save(@AuthenticationPrincipal JwtAuthenticationToken token,
					@Valid @RequestBody Message message) {
	message.setCreated(Calendar.getInstance());
	message = this.messageRepository.save(message);
	if (hasAuthority(token, CONTACTS_AUTHORITY)) {
		return addUserInformation(message);
	}
	return message;
}
 
Example #24
Source File: ServiceCController.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@GetMapping
public ServiceCallResponse serviceC(JwtAuthenticationToken jwtAuthentication,
									HttpServletRequest request) {
	ServiceCallResponse serviceCallResponse = new ServiceCallResponse();
	serviceCallResponse.setServiceName(SERVICE_C);
	serviceCallResponse.setServiceUri(request.getRequestURL().toString());
	serviceCallResponse.setJti(jwtAuthentication.getToken().getId());
	serviceCallResponse.setSub(jwtAuthentication.getToken().getSubject());
	serviceCallResponse.setAud(jwtAuthentication.getToken().getAudience());
	serviceCallResponse.setAuthorities(jwtAuthentication.getAuthorities().stream()
			.map(GrantedAuthority::getAuthority).sorted().collect(Collectors.toList()));

	return serviceCallResponse;
}
 
Example #25
Source File: ServiceAController.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@GetMapping
public ServiceCallResponse serviceA(JwtAuthenticationToken jwtAuthentication,
									HttpServletRequest request) {
	ServiceCallResponse serviceCallResponse = new ServiceCallResponse();
	serviceCallResponse.setServiceName(SERVICE_A);
	serviceCallResponse.setServiceUri(request.getRequestURL().toString());
	serviceCallResponse.setJti(jwtAuthentication.getToken().getId());
	serviceCallResponse.setSub(jwtAuthentication.getToken().getSubject());
	serviceCallResponse.setAud(jwtAuthentication.getToken().getAudience());
	serviceCallResponse.setAuthorities(jwtAuthentication.getAuthorities().stream()
			.map(GrantedAuthority::getAuthority).sorted().collect(Collectors.toList()));

	return serviceCallResponse;
}
 
Example #26
Source File: ServiceBTokenExchangeController.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@GetMapping
public ServiceCallResponse serviceB_TokenExchange(JwtAuthenticationToken jwtAuthentication,
													HttpServletRequest request) {

	ServiceCallResponse serviceCCallResponse = callServiceC("client-c-exchange");
	return fromServiceB(jwtAuthentication, request, serviceCCallResponse);
}
 
Example #27
Source File: ServiceBTokenRelayController.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@GetMapping
public ServiceCallResponse serviceB_TokenRelay(JwtAuthenticationToken jwtAuthentication,
												HttpServletRequest request) {

	ServiceCallResponse serviceCCallResponse = callServiceC(jwtAuthentication.getToken());
	return fromServiceB(jwtAuthentication, request, serviceCCallResponse);
}
 
Example #28
Source File: ServiceBClientCredentialsController.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@GetMapping
public ServiceCallResponse serviceB_ClientCredentials(JwtAuthenticationToken jwtAuthentication,
														HttpServletRequest request) {

	ServiceCallResponse serviceCCallResponse = callServiceC("client-c");
	return fromServiceB(jwtAuthentication, request, serviceCCallResponse);
}
 
Example #29
Source File: ProductCompositeServiceImpl.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private void logAuthorizationInfo(SecurityContext sc) {
    if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) {
        Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken();
        logAuthorizationInfo(jwtToken);
    } else {
        LOG.warn("No JWT based Authentication supplied, running tests are we?");
    }
}
 
Example #30
Source File: TestController.java    From oauth2-resource with MIT License 4 votes vote down vote up
@GetMapping("/cat/list")
public Map<String, Object> catList(JwtAuthenticationToken authenticationToken) {
    Map<String, Object> result = new HashMap<>(16);
    result.put("status", 1);
    return result;
}