Java Code Examples for org.springframework.security.core.Authentication#getPrincipal()
The following examples show how to use
org.springframework.security.core.Authentication#getPrincipal() .
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: FooAuthenticationProvider.java From spring-auth-example with MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.debug( "==== Authenticating using FooAuthenticationProvider: " + authentication); // here goes username/password authentication for Foo Response response = userService .authenticateFoo(String.valueOf(authentication.getPrincipal()), String.valueOf(authentication.getCredentials())); if (response.isOk()) { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("FOO_READ")); authorities.add(new SimpleGrantedAuthority("FOO_WRITE")); return new FooUsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), authorities); } else { throw new BadCredentialsException("Authentication failed."); } }
Example 2
Source File: JsonWebTokenAuthenticationProvider.java From trivia-microservices with MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication authenticatedUser = null; // Only process the PreAuthenticatedAuthenticationToken if (authentication.getClass().isAssignableFrom(PreAuthenticatedAuthenticationToken.class) && authentication.getPrincipal() != null) { String tokenHeader = (String) authentication.getPrincipal(); UserDetails userDetails = parseToken(tokenHeader); if (userDetails != null) { authenticatedUser = new JsonWebTokenAuthentication(userDetails, tokenHeader); } } else { // It is already a JsonWebTokenAuthentication authenticatedUser = authentication; } return authenticatedUser; }
Example 3
Source File: UserResource.java From angular-rest-springsecurity with Apache License 2.0 | 6 votes |
/** * Authenticates a user and creates an access token. * * @param username The name of the user. * @param password The password of the user. * @return The generated access token. */ @Path("authenticate") @POST @Produces(MediaType.APPLICATION_JSON) public AccessToken authenticate(@FormParam("username") String username, @FormParam("password") String password) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); Authentication authentication = this.authManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); Object principal = authentication.getPrincipal(); if (!(principal instanceof User)) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } return this.userService.createAccessToken((User) principal); }
Example 4
Source File: DashboardServiceImpl.java From mirrorgate with Apache License 2.0 | 6 votes |
@Override public DashboardDTO updateDashboard(final String dashboardName, final DashboardDTO updatedDashboard) { final Dashboard currentDashboard = this.getRepositoryDashboard(dashboardName); final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String authUser = "anonymous"; if (auth != null) { authUser = (String) auth.getPrincipal(); canEdit(authUser, currentDashboard); } if (updatedDashboard.getAdminUsers() == null) { updatedDashboard.setAdminUsers(Collections.singletonList(authUser)); } else if (!updatedDashboard.getAdminUsers().contains(authUser)) { updatedDashboard.getAdminUsers().add(authUser); } final Dashboard toSave = mergeDashboard(currentDashboard, map(updatedDashboard), authUser); final Dashboard saved = dashboardRepository.save(toSave); eventService.saveEvent(saved, EventType.DETAIL); return map(saved); }
Example 5
Source File: AuthenticationController.java From spring-boot-start-current with Apache License 2.0 | 6 votes |
/** * 认证 * * @param user : 表单 * @return token * @throws AuthenticationException 认证失败则会抛异常 */ @PostMapping public ResponseEntity createAuthenticationToken ( @Validated( ValidatedGroups.Special.class ) @RequestBody UserForm user) throws AuthenticationException { // 执行安全认证 final Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( user.getUsername() , user.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication( authentication ); final UserDetails userDetails = ( UserDetails ) authentication.getPrincipal(); final String token = jwtTokenUtil.generateToken( userDetails ); // 返回 return new ResponseEntityPro().add( "token" , token ) .add( "user" , userDetails ) .flushBodyByFilterFields( "*,-user.password,-user.lastPasswordResetDate,-user.createTime,-user.updateTime,-user.remark,-user.enabled" ).buildOk(); }
Example 6
Source File: SpringSecurityUserContext.java From Spring-Security-Third-Edition with MIT License | 6 votes |
/** * 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 7
Source File: InsightsSAMLTokenAuthenticationImpl.java From Insights with Apache License 2.0 | 6 votes |
/** * This method is used to validate all subsequent request token * */ @Override public Authentication authenticate(Authentication authentication) throws InsightsAuthenticationException { LOG.debug("Inside InsightsAuthenticationProviderImpl === "); if (!supports(authentication.getClass())) { throw new IllegalArgumentException("Only SAMLAuthenticationToken is supported, " + authentication.getClass() + " was attempted"); } if (authentication.getPrincipal() == null) { LOG.debug("Authentication token is missing - authentication.getPrincipal() {} ", authentication.getPrincipal()); throw new AuthenticationCredentialsNotFoundException("Authentication token is missing"); } /*validate request token*/ validateIncomingToken(authentication.getPrincipal()); return authentication; }
Example 8
Source File: AuthController.java From sk-admin with Apache License 2.0 | 5 votes |
@Log("用户登录") @ApiOperation("登录授权") @AnonymousAccess @PostMapping(value = "/login") public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDTO authUser, HttpServletRequest request) { // 密码解密 RSA rsa = new RSA(privateKey, null); String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey)); // 查询验证码 String code = (String) redisUtils.get(authUser.getUuid()); // 清除验证码 redisUtils.del(authUser.getUuid()); if (StringUtils.isBlank(code)) { throw new SkException("验证码不存在或已过期"); } if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) { throw new SkException("验证码错误"); } UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUser.getUsername(), password); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); // 生成令牌 String token = tokenProvider.createToken(authentication); final JwtUserDTO jwtUserDto = (JwtUserDTO) authentication.getPrincipal(); // 保存在线信息 onlineUserService.save(jwtUserDto, token, request); // 返回 token 与 用户信息 Map<String, Object> authInfo = new HashMap<String, Object>(4) {{ put("token", properties.getTokenStartWith() + token); put("user", jwtUserDto); }}; if (singleLogin) { //踢掉之前已经登录的token onlineUserService.checkLoginOnUser(authUser.getUsername(), token); } return ResponseEntity.ok(authInfo); }
Example 9
Source File: SecurityUtils.java From cloud-template with MIT License | 5 votes |
/** * 获取用户名 * * @return */ public String getUsername() { Authentication authentication = getAuthentication(); Object principal = authentication.getPrincipal(); if (!(principal instanceof SctUser)) { return (String) principal; } return null; }
Example 10
Source File: DefaultPermissionEvaluator.java From blog-sample with Apache License 2.0 | 5 votes |
@Override public boolean hasPermission(Authentication authentication, Object targetUrl, Object targetPermission) { // 获得loadUserByUsername()方法的结果 User user = (User)authentication.getPrincipal(); // 获得loadUserByUsername()中注入的角色 Collection<GrantedAuthority> authorities = user.getAuthorities(); // 遍历用户所有角色 for(GrantedAuthority authority : authorities) { String roleName = authority.getAuthority(); Integer roleId = roleService.getByName(roleName).getId(); // 得到角色所有的权限 List<SysPermission> permissionList = permissionService.listByRoleId(roleId); // 遍历permissionList for(SysPermission sysPermission : permissionList) { // 获取权限集 List permissions = sysPermission.getPermissions(); // 如果访问的Url和权限用户符合的话,返回true if(targetUrl.equals(sysPermission.getUrl()) && permissions.contains(targetPermission)) { return true; } } } return false; }
Example 11
Source File: SpringSecurityListener.java From lemon with Apache License 2.0 | 5 votes |
public String getTenantId(Authentication authentication) { if (authentication == null) { return ""; } Object principal = authentication.getPrincipal(); if (principal instanceof SpringSecurityUserAuth) { return ((SpringSecurityUserAuth) principal).getTenantId(); } else { return ""; } }
Example 12
Source File: AuthUtils.java From microservices-platform with Apache License 2.0 | 5 votes |
/** * 获取登陆的用户名 */ public static String getUsername(Authentication authentication) { Object principal = authentication.getPrincipal(); String username = null; if (principal instanceof SysUser) { username = ((SysUser) principal).getUsername(); } else if (principal instanceof String) { username = (String) principal; } return username; }
Example 13
Source File: SecurityUtils.java From expper with GNU General Public License v3.0 | 5 votes |
/** * Get the login of the current user. */ public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; }
Example 14
Source File: AccessControlServiceUserOwned.java From QuizZz with MIT License | 5 votes |
private AuthenticatedUser getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication.getPrincipal() == null || authentication.getPrincipal() instanceof String) { return null; } return (AuthenticatedUser) authentication.getPrincipal(); }
Example 15
Source File: BaseController.java From iotplatform with Apache License 2.0 | 5 votes |
protected SecurityUser getCurrentUser() throws IoTPException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof SecurityUser) { return (SecurityUser) authentication.getPrincipal(); } else { throw new IoTPException("You aren't authorized to perform this operation!", IoTPErrorCode.AUTHENTICATION); } }
Example 16
Source File: GlobalControllerAdvice.java From spring-boot with Apache License 2.0 | 5 votes |
/** * 执行每个 url 时,都检查是否经过验证,把返回值放入 Model * * @param authentication 会被 * @return 返回值 和 CustomUserDetailsService 的返回值org.springframework.security.core.userdetails.User 为 UserDetails类型 * --- * @ModelAttribute 会把键值对,放入到全局 ,所有注解 @RequstMapping 的方法,均可以获得到。 * 本例中,把获得的用户信息,放入到全局 Model * --- * public void getSomething(@ModelAttribute("currentUser") SecurityUser user) { * user.get... * //此处可以获得 @ModelAttribute 放入 Model 中的信息 UserDetails * } * --- */ // @ModelAttribute 在方法上注解 : // 1. 则会在 spring context 中查找属性名为 authentication 的对象,并把该对象赋值给该方法的参数。 // 本例中 authentication 参数会被自动赋值为 SecurityContextHolder.getContext().getAuthentication() // 2. 该方法的返回值,以 @ModelAttribute 的 value 值为名字,放入 Model,可以在页面段获取。 // 在本项目中 : 可以通过 currentUser.username 获得用户名 (username 为 UserDetails 属性) @ModelAttribute(value = "currentUser") // currentUser 在页面端用到 public UserDetails getCurrentUser(Authentication authentication) { //如果 loadUserByUsername 没有找到用户,会返回 返回用户名 anonymousUser 的用户默认用户 // 下面 log 的结果为测试信息 // is isAuthenticated() ? true // Authentication name : anonymousUser // if (authentication != null) { // log.info("is isAuthenticated() ? " + SecurityContextHolder.getContext().getAuthentication().isAuthenticated()); // log.info("Authentication name : " + SecurityContextHolder.getContext().getAuthentication().getName()); // log.info("getCredentials name : " + SecurityContextHolder.getContext().getAuthentication().getCredentials()); // log.info("getDetails name : " + SecurityContextHolder.getContext().getAuthentication().getDetails()); // for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) // log.info("authority(role) : " + authority.getAuthority()); // // //测试验证对象类型 // Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // if (principal instanceof UserDetails) { // log.info("loadUserByUsername 的返回值类型是 UserDetails : " + ((UserDetails) principal).getUsername()); // } // if (principal instanceof Principal) { // log.info("loadUserByUsername 的返回值类型是 Principal : " + ((Principal) principal).getName()); // } // } else { // log.info("authentication is null."); // } return (authentication == null) ? null : (UserDetails) authentication.getPrincipal(); }
Example 17
Source File: AuthenticatedUserService.java From cloudbreak with Apache License 2.0 | 5 votes |
public String getServiceAccountId() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof CrnUser) { CrnUser user = (CrnUser) authentication.getPrincipal(); return user.getTenant(); } return ""; }
Example 18
Source File: LdapAuthFilter.java From para with Apache License 2.0 | 4 votes |
private UserAuthentication getOrCreateUser(App app, Authentication ldapAuth) { LOG.debug("LDAP response: {}", ldapAuth); if (ldapAuth == null) { return null; } UserAuthentication userAuth = null; User user = new User(); InetOrgPerson profile = (InetOrgPerson) ldapAuth.getPrincipal(); if (profile != null && profile.isEnabled() && profile.isAccountNonLocked() && profile.isAccountNonExpired()) { String ldapAccountId = profile.getUsername(); String email = profile.getMail(); String name = StringUtils.join(profile.getCn(), ", "); String adDomain = (String) app.getSetting("security.ldap.active_directory_domain"); String groups = getGroupsFromDN(profile.getDn(), app); if (StringUtils.isBlank(email)) { if (Utils.isValidEmail(ldapAccountId)) { email = ldapAccountId; } else if (!StringUtils.isBlank(adDomain)) { LOG.warn("The AD doesn't have email attribute. Instead, it uses domain name for email address: " + "{}@{}.", ldapAccountId, adDomain); email = ldapAccountId.concat("@").concat(adDomain); } else { LOG.warn("Blank email attribute for LDAP user '{}'.", ldapAccountId); email = ldapAccountId + "@paraio.com"; } } if (Boolean.parseBoolean(app.getSetting("security.ldap.username_as_name") + "")) { name = email.split("@")[0]; } user.setAppid(getAppid(app)); user.setIdentifier(Config.LDAP_PREFIX.concat(ldapAccountId)); user.setEmail(email); user = User.readUserForIdentifier(user); if (user == null) { //user is new user = new User(); user.setActive(true); user.setAppid(getAppid(app)); user.setEmail(email); user.setGroups(groups); user.setName(StringUtils.isBlank(name) ? "No Name" : name); user.setPassword(Utils.generateSecurityToken()); user.setIdentifier(Config.LDAP_PREFIX.concat(ldapAccountId)); String id = user.create(); if (id == null) { throw new AuthenticationServiceException("Authentication failed: cannot create new user."); } } else { if (updateUserInfo(user, email, name, groups)) { user.update(); } } userAuth = new UserAuthentication(new AuthenticatedUserDetails(user)); } else { LOG.error("Failed to create account - is the LDAP user active? principal={}", profile); } return userAuth; }
Example 19
Source File: AbstractAuthenticationResource.java From gravitee-management-rest-api with Apache License 2.0 | 4 votes |
protected Response connectUser(String userId,final String state, final HttpServletResponse servletResponse) { UserEntity user = userService.connect(userId); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final UserDetails userDetails = (UserDetails) authentication.getPrincipal(); // Manage authorities, initialize it with dynamic permissions from the IDP List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList()); // We must also load permissions from repository for configured management or portal role Set<RoleEntity> userRoles = membershipService.getRoles( MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId()); if (!userRoles.isEmpty()) { userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build())); } userRoles = membershipService.getRoles( MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId()); if (!userRoles.isEmpty()) { userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build())); } // JWT signer Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret")); Date issueAt = new Date(); Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER))); final String token = JWT.create() .withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)) .withIssuedAt(issueAt) .withExpiresAt(Date.from(expireAt)) .withSubject(user.getId()) .withClaim(JWTHelper.Claims.PERMISSIONS, authorities) .withClaim(JWTHelper.Claims.EMAIL, user.getEmail()) .withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()) .withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()) .withJWTId(UUID.randomUUID().toString()) .sign(algorithm); final TokenEntity tokenEntity = new TokenEntity(); tokenEntity.setType(BEARER); tokenEntity.setToken(token); if (state != null && !state.isEmpty()) { tokenEntity.setState(state); } final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token); servletResponse.addCookie(bearerCookie); return Response .ok(tokenEntity) .build(); }
Example 20
Source File: RoleAccessDecisionManager.java From jvue-admin with MIT License | 4 votes |
@Override public void decide(Authentication authentication, Object arg1, Collection<ConfigAttribute> arg2) throws AccessDeniedException, InsufficientAuthenticationException { // TODO Auto-generated method stub logger.debug("arg0 {}, arg1 {}, arg2 {}", authentication, arg1, arg2); // 逻辑 if (arg1 instanceof FilterInvocation) { // HTTP filter object FilterInvocation filterInvocation = (FilterInvocation) arg1; // // 1.判断是否为超级管理员,是的话直接放行 // if (authentication.getPrincipal() instanceof JwtUserDetails) { // JwtUserDetails jwtUser = (JwtUserDetails) authentication.getPrincipal(); // if (jwtUser.getSuperUser() == JvueDataStatus.SUPER_USER_TRUE) { // // 放行 // logger.debug("SUPER_USER_TRUE"); // return ; // } // } // 1.判断URL对应的权限定义 MultiMap<Integer, AclResource> resourcesMap = hazelcastInstance.getMultiMap("acl-resource"); // >> arg1 FilterInvocation: URL: /module?page=0&pageSize=10 // >> 如果不需要登录的话,直接放行 String requestUrl = filterInvocation.getRequestUrl(); String requestMethod = filterInvocation.getRequest().getMethod(); Integer apiCode = null; logger.debug("访问接口:{} {}", requestUrl, requestMethod); for (AclResource ar: resourcesMap.values()) { if (ar.getType() == AclResource.Type.METHOD) { //pathHelper. boolean isUrl = false; boolean isMethod = false; logger.trace("判断接口:{} {} {}, {}", ar.getCode(), ar.getName(), ar.getPath(), ar.getPattern()); for (String path : ar.getPattern()) { isUrl = pathMatcher.match(path, requestUrl); if (isUrl) { break; } } if (isUrl) { if (ar.getMethod() != null) { for (String method: ar.getMethod()) { if (Objects.equals(method, requestMethod)){ isMethod = true; break; } } } else { isMethod = true; } } if (isUrl && isMethod) { // 已匹配 apiCode = ar.getId(); logger.debug("已匹配接口:{} > {} {}", requestUrl, ar.getCode(), ar.getName()); break; } } } if (apiCode != null ) { // 取对应的角色权限 List<Integer> roles = jvueRoleService.getRolesByApi(apiCode); if (!roles.isEmpty()) { // 2.判断是否为超级管理员,是的话直接放行 if (authentication.getPrincipal() instanceof JwtUserDetails) { JwtUserDetails jwtUser = (JwtUserDetails) authentication.getPrincipal(); Collection<Integer> intersection = CollectionUtils.intersection(roles, jwtUser.getRoles()); if (intersection.isEmpty()) { // 没有匹配到角色 throw new AccessDeniedException("no role"); } } } } // 处理 apiCode与角色匹配 // 3.获取用户的角色,通过比对角色授予的API接口ID和AclResource里定义的ID,有匹配则放行 // 4.上述以外,禁止调用 // TODO throw new AccessDeniedException("no role"); } }