当前位置: 首页>>代码示例>>Java>>正文


Java Authentication.getName方法代码示例

本文整理汇总了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);
    }
}
 
开发者ID:mingzuozhibi,项目名称:mzzb-server,代码行数:25,代码来源:SessionController.java

示例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));
    }
}
 
开发者ID:hzwy23,项目名称:hauth-java,代码行数:19,代码来源:CustomAuthenticationProvider.java

示例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);
    }
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:25,代码来源:CustomPersistentRememberMeServices.java

示例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";
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:18,代码来源:ManagerCardController.java

示例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);
	}
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:18,代码来源:StatsController.java

示例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);
	}
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:19,代码来源:CardEtatService.java

示例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);
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:16,代码来源:YadaAuthenticationSuccessHandler.java

示例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";
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:14,代码来源:UserCardController.java

示例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");
	}
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:15,代码来源:AppHRProvider.java

示例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";
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:12,代码来源:UserCardController.java

示例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;
}
 
开发者ID:EsupPortail,项目名称:esup-sgc,代码行数:10,代码来源:ManagerCardController.java

示例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();
        }
    };
}
 
开发者ID:weechang,项目名称:Taroco,代码行数:16,代码来源:UCQueryApplication.java

示例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();
    }
}
 
开发者ID:zhaojunfei,项目名称:lemon,代码行数:14,代码来源:LogoutSuccessHandlerImpl.java

示例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


注:本文中的org.springframework.security.core.Authentication.getName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。