本文整理匯總了Java中org.springframework.security.core.Authentication.getName方法的典型用法代碼示例。如果您正苦於以下問題:Java Authentication.getName方法的具體用法?Java Authentication.getName怎麽用?Java Authentication.getName使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.springframework.security.core.Authentication
的用法示例。
在下文中一共展示了Authentication.getName方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: status
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@GetMapping(value = "/api/session", produces = CONTENT_TYPE)
public String status() {
logger.info("狀態獲取: 正在檢測登入狀態");
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
String username = authentication.getName();
if (!"anonymousUser".equals(username)) {
logger.info("狀態獲取: 檢測到已登入用戶, username={}", username);
JSONObject object = new JSONObject();
object.put("success", true);
object.put("username", username);
putAuthority(object, authentication);
return object.toString();
} else {
logger.info("狀態獲取: 檢測到匿名用戶");
return booleanResult(false);
}
} else {
logger.info("狀態獲取: 未檢測到已登入狀態");
return booleanResult(false);
}
}
示例2: authenticate
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@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));
}
}
示例3: authenticate
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final String username = authentication.getName();
final String password = authentication.getCredentials().toString();
User user = null;
try {
user = userService.doesUserExist(username);
} catch (UserNotFoundException e) {
}
if (user == null || !user.getEmail().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
if(user.getRole() == 1) {
authorities.add(new SimpleGrantedAuthority("ROLE_DOCTOR"));
} else {
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
}
final UserDetails principal = new org.springframework.security.core.userdetails.User(username, password, authorities);
return new UsernamePasswordAuthenticationToken(principal, password, authorities);
}
開發者ID:PacktPublishing,項目名稱:Building-Web-Apps-with-Spring-5-and-Angular,代碼行數:27,代碼來源:CustomAuthenticationProvider.java
示例4: 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(generateSeriesData());
t.setUser(u);
t.setTokenValue(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.save(token);
addCookie(token, request, response);
} catch (DataAccessException e) {
log.error("Failed to save persistent token ", e);
}
}
示例5: savePrefs
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@RequestMapping(value="/savePrefs")
public String savePrefs(@RequestParam(value="editable", required=false) String editable, @RequestParam(value="ownOrFreeCard", required=false) String ownOrFreeCard, Model uiModel) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String eppn = auth.getName();
editable = (editable!= null)? "true" : "all";
ownOrFreeCard = (ownOrFreeCard!= null)? "true" : "false";
uiModel.asMap().clear();
try {
preferencesService.setPrefs(eppn, "EDITABLE", editable);
preferencesService.setPrefs(eppn, "OWNORFREECARD", ownOrFreeCard);
} catch (Exception e) {
log.warn("Impossible de sauvegarder les préférences", e);
}
return "redirect:/manager?index=first";
}
示例6: savePrefs
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@RequestMapping(value="/prefs", headers = "Accept=application/json; charset=utf-8")
@ResponseBody
public void savePrefs(@RequestParam List<String> values, @RequestParam String key) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String eppn = auth.getName();
try {
preferencesService.setPrefs(eppn, key, StringUtils.join(values, ","));
if(KEYRM.equals(key)){
List <String> prefsStats = new ArrayList<String>(Arrays.asList(preferencesService.getPrefs(eppn, KEY).getValue().split("\\s*,\\s*")));
prefsStats.remove(values.get(0));
}
} catch (Exception e) {
log.warn("Impossible de sauvegarder les préférences", e);
}
}
示例7: updateEtatsAvailable4Card
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public void updateEtatsAvailable4Card(Card card) {
String eppn = "system";
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null) {
eppn = auth.getName();
}
card.setEtatsAvailable(workflow.get(card.getEtat()));
if(Etat.IN_PRINT.equals(card.getEtat()) || Etat.IN_ENCODE.equals(card.getEtat())) {
if(!eppn.equals(card.getEtatEppn())) {
card.setEtatsAvailable(new ArrayList<Etat>());
}
}
if(Etat.NEW.equals(card.getEtat()) && card.getUser()!=null && !card.getUser().isEditable()) {
List<Etat> etatsAvailable = new ArrayList<Etat>(card.getEtatsAvailable());
etatsAvailable.remove(Etat.REQUEST_CHECKED);
card.setEtatsAvailable(etatsAvailable);
}
}
示例8: onAuthenticationSuccess
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
String username = authentication.getName();
userCredentialsRepository.updateLoginTimestamp(username.toLowerCase());
// Quando il login ha successo, resetto il contatore dei tentativi falliti che altrimenti cresce sempre finchè non sbaglio due volte (!)
userCredentialsRepository.resetFailedAttempts(username.toLowerCase());
// String redirectUrl = "/register"; // !!!!!!!!!!!!!!
// request.setAttribute("redirectUrl", redirectUrl);
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
super.setDefaultTargetUrl(defaultTargetUrlAjaxRequest);
} else {
super.setDefaultTargetUrl(defaultTargetUrlNormalRequest);
}
super.onAuthenticationSuccess(request, response, authentication);
}
示例9: deliver
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@RequestMapping(value="/deliver/{cardId}", method=RequestMethod.POST)
@Transactional
public String deliver(@PathVariable("cardId") Long cardId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String eppn = auth.getName();
Card card = Card.findCard(cardId);
if(eppn.equals(card.getEppn())) {
card.setDeliveredDate(new Date());
card.merge();
logService.log(card.getId(), ACTION.USER_DELIVERY, RETCODE.SUCCESS, "", card.getEppn(), null);
}
return "redirect:/user";
}
示例10: authenticate
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
System.out.println(AppHRProvider.class);
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if (name.equalsIgnoreCase("hradmin") && password.equalsIgnoreCase("hradmin")) {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority("ROLE_HR"));
return new UsernamePasswordAuthenticationToken(name, password,authorities);
} else {
throw new BadCredentialsException("Invalid HR User");
}
}
示例11: enableEuropeanCard
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@RequestMapping(value="/enableEuropeanCard", method=RequestMethod.POST)
public String enableEuropeanCard(final RedirectAttributes redirectAttributes) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String eppn = auth.getName();
User user = User.findUser(eppn);
user.setEuropeanStudentCard(true);
user.merge();
logService.log(user.getCards().get(0).getId(), ACTION.ENABLEEUROPEANCARD, RETCODE.SUCCESS, "", eppn, null);
redirectAttributes.addFlashAttribute("messageInfo", SUCCESS_MSG + "european");
return "redirect:/user";
}
示例12: getuserPrefs
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@ModelAttribute("userPrefs")
public HashedMap getuserPrefs() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String eppn = auth.getName();
HashedMap mapPrefs= new HashedMap();
mapPrefs.put("editable", preferencesService.getPrefValue(eppn, "EDITABLE"));
mapPrefs.put("ownOrFreeCard", preferencesService.getPrefValue(eppn, "OWNORFREECARD"));
return mapPrefs;
}
示例13: auditorAware
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Bean
public AuditorAware<String> auditorAware() {
return new AuditorAware<String>() {
@Override
public String getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
return authentication.getName();
}
};
}
示例14: getUserId
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public String getUserId(Authentication authentication) {
if (authentication == null) {
return "";
}
Object principal = authentication.getPrincipal();
if (principal instanceof SpringSecurityUserAuth) {
return ((SpringSecurityUserAuth) principal).getId();
} else {
return authentication.getName();
}
}
示例15: hasPermission
import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
private boolean hasPermission(Authentication authentication, Event event, Object permission) {
if(event == null) {
return true;
}
String currentUserEmail = authentication.getName();
String ownerEmail = extractEmail(event.getOwner());
if("write".equals(permission)) {
return currentUserEmail.equals(ownerEmail);
} else if("read".equals(permission)) {
String attendeeEmail = extractEmail(event.getAttendee());
return currentUserEmail.equals(attendeeEmail) || currentUserEmail.equals(ownerEmail);
}
throw new IllegalArgumentException("permission "+permission+" is not supported.");
}
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:15,代碼來源:CalendarPermissionEvaluator.java