本文整理汇总了Java中org.springframework.security.core.Authentication类的典型用法代码示例。如果您正苦于以下问题:Java Authentication类的具体用法?Java Authentication怎么用?Java Authentication使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Authentication类属于org.springframework.security.core包,在下文中一共展示了Authentication类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createAcl
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@Override
public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException {
Assert.notNull(objectIdentity, "Object Identity required");
// Check this object identity hasn't already been persisted
if (retrieveObjectIdentityPrimaryKey(objectIdentity) != null) {
throw new AlreadyExistsException("Object identity '" + objectIdentity + "' already exists");
}
// Need to retrieve the current principal, in order to know who "owns" this ACL (can be changed later on)
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
PrincipalSid sid = new PrincipalSid(auth);
// Create the acl_object_identity row
createObjectIdentity(objectIdentity, sid);
// Retrieve the ACL via superclass (ensures cache registration, proper retrieval etc)
Acl acl = readAclById(objectIdentity);
Assert.isInstanceOf(MutableAcl.class, acl, "MutableAcl should be been returned");
return (MutableAcl) acl;
}
示例2: auth
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@RequestMapping(value = "auth", method = RequestMethod.POST)
public ResponseEntity<?> auth(@RequestBody AuthRequest ar) {
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(ar.getUsername(), ar.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
User u = userRepository.findByUsername(ar.getUsername());
if (u != null) {
String token = jwtTokenUtil.generateToken(u);
return ResponseEntity.ok(new AuthResponse(token));
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
}
示例3: authorize
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@PostMapping("/authenticate")
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException exception) {
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例4: doFilter
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
try {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String jwt = resolveToken(httpServletRequest);
if (StringUtils.hasText(jwt)) {
if (this.tokenProvider.validateToken(jwt)) {
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(servletRequest, servletResponse);
} catch (ExpiredJwtException eje) {
log.info("Security exception for user {} - {}", eje.getClaims().getSubject(), eje.getMessage());
((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
示例5: authenticate
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@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;
}
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:21,代码来源:CalendarUserAuthenticationProvider.java
示例6: doFilterInternal
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String username = jwtTokenUtil.getUsername(request);
System.out.println("checking authentication " + username);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
if (jwtTokenUtil.validate(request)) {
Authentication authentication = jwtTokenUtil.
getAuthentication(request);
System.out.println("authenticated user " + username + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
KeyUserInfo keyUserInfo = userRepository.findByEmail(username).get(0);
System.out.println(keyUserInfo.getId());
ZuulFilterConfig.setUid(keyUserInfo.getId());
}
}
chain.doFilter(request, response);
}
示例7: createAuthenticationToken
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device)
throws AuthenticationException {
// Perform the security
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Reload password post-security so we can generate token
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails, device);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
示例8: onLoginSuccess
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
successfulAuthentication) {
String login = successfulAuthentication.getName();
log.debug("Creating new persistent login for user {}", login);
PersistentToken token = userRepository.findOneByLogin(login).map(u -> {
PersistentToken t = new PersistentToken();
t.setSeries(RandomUtil.generateSeriesData());
t.setUser(u);
t.setTokenValue(RandomUtil.generateTokenData());
t.setTokenDate(LocalDate.now());
t.setIpAddress(request.getRemoteAddr());
t.setUserAgent(request.getHeader("User-Agent"));
return t;
}).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database"));
try {
persistentTokenRepository.saveAndFlush(token);
addCookie(token, request, response);
} catch (DataAccessException e) {
log.error("Failed to save persistent token ", e);
}
}
示例9: getCurrentUser
import org.springframework.security.core.Authentication; //导入依赖的package包/类
/**
* 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;
}
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:28,代码来源:SpringSecurityUserContext.java
示例10: createJwtToken
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@Override
public String createJwtToken(Authentication authentication, int minutes) {
Claims claims = Jwts.claims()
.setId(String.valueOf(IdentityGenerator.generate()))
.setSubject(authentication.getName())
.setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000))
.setIssuedAt(new Date());
String authorities = authentication.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.map(String::toUpperCase)
.collect(Collectors.joining(","));
claims.put(AUTHORITIES, authorities);
return Jwts.builder()
.setClaims(claims)
.signWith(HS512, secretkey)
.compact();
}
示例11: createToken
import org.springframework.security.core.Authentication; //导入依赖的package包/类
public String createToken(Authentication authentication, Boolean rememberMe) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInMilliseconds);
}
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(SignatureAlgorithm.HS512, secretKey)
.setExpiration(validity)
.compact();
}
示例12: onLogoutSuccess
import org.springframework.security.core.Authentication; //导入依赖的package包/类
public void onLogoutSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
super.handle(request, response, authentication);
if (authentication == null) {
logger.info("authentication is null");
return;
}
String tenantId = tenantHolder.getTenantId();
String userId = this.getUserId(authentication);
String sessionId = this.getSessionId(authentication);
LogoutEvent logoutEvent = new LogoutEvent(authentication, userId,
sessionId, tenantId);
ctx.publishEvent(logoutEvent);
}
示例13: authenticate
import org.springframework.security.core.Authentication; //导入依赖的package包/类
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
UaaRelyingPartyToken auth = (UaaRelyingPartyToken) authentication;
Map<String, Object> tokenObj = UaaFilterUtils.verifiedToken(auth.getToken(), publicKey);
UaaUserDetails userDetails = new UaaUserDetails();
userDetails.setUsername(tokenObj.get(Properties.USER_NAME).toString());
userDetails.setGrantedAuthorities(scopeToGrantedAuthority((List<String>) tokenObj.get(Properties.SCOPE)));
if (!userDetails.isEnabled()) {
throw new AuthenticationServiceException("User is disabled");
}
return createSuccessfulAuthentication(userDetails);
}
示例14: getCurrentUser
import org.springframework.security.core.Authentication; //导入依赖的package包/类
/**
* 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;
}
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:26,代码来源:SpringSecurityUserContext.java
示例15: actionEtat
import org.springframework.security.core.Authentication; //导入依赖的package包/类
@PreAuthorize("hasRole('ROLE_MANAGER')")
@RequestMapping(value="/action/{cardId}", method=RequestMethod.POST)
@Transactional
public String actionEtat(@PathVariable("cardId") Long cardId, @RequestParam Etat etatFinal, @RequestParam(required=false) String comment, Model uiModel) {
Card card = Card.findCard(cardId);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String eppn = auth.getName();
if(Etat.IN_PRINT.equals(etatFinal) && (Etat.REQUEST_CHECKED.equals(card.getEtat()) || eppn.equals(card.getEtatEppn()))) {
if(cardEtatService.setCardEtat(card, etatFinal, comment, comment, true, false)) {
uiModel.addAttribute("cards", Arrays.asList(new Card[]{card}));
}
uiModel.addAttribute("cardMask", appliConfigService.getCardMask());
uiModel.addAttribute("cardLogo", appliConfigService.getCardLogo());
return "manager/print-card";
} else {
uiModel.asMap().clear();
cardEtatService.setCardEtat(card, etatFinal, comment, comment, true, false);
return "redirect:/manager/" + card.getId();
}
}