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


Java User类代码示例

本文整理汇总了Java中org.springframework.security.core.userdetails.User的典型用法代码示例。如果您正苦于以下问题:Java User类的具体用法?Java User怎么用?Java User使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


User类属于org.springframework.security.core.userdetails包,在下文中一共展示了User类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAuthentication

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
public Authentication getAuthentication(String token) {
    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

    Collection<? extends GrantedAuthority> authorities =
        Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());

    User principal = new User(claims.getSubject(), "",
        authorities);

    return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
 
开发者ID:IBM,项目名称:Microservices-with-JHipster-and-Spring-Boot,代码行数:17,代码来源:TokenProvider.java

示例2: getAuthentication

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
public Authentication getAuthentication(String token) {
    Claims claims = Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody();

    Collection<? extends GrantedAuthority> authorities =
        Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream()
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());

    User principal = new User(claims.getSubject(), "",
        authorities);

    return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
 
开发者ID:klask-io,项目名称:klask-io,代码行数:17,代码来源:TokenProvider.java

示例3: getCurrentUser

import org.springframework.security.core.userdetails.User; //导入依赖的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;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        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);
        }
        return result;
    }
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:27,代码来源:SpringSecurityUserContext.java

示例4: testGetExistingAccount

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
@Test
public void testGetExistingAccount() throws Exception {

    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);

    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));

    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));

    mock.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("user"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
开发者ID:oktadeveloper,项目名称:jhipster-microservices-example,代码行数:21,代码来源:AccountResourceTest.java

示例5: loadUserByUsername

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
	//System.err.println("-----------MyUserDetailServiceImpl loadUserByUsername ----------- ");
	//取得用户的权限
	Customer user = authService.findCustomer(userName);
	if  (user==null)  
           throw new UsernameNotFoundException(userName+" not exist!");  
	Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
	// 封装成spring security的user
	User userdetail = new User(
			user.getName(), 
			user.getPassword(),
			true, 
			true, 
			true,
			true, 
			grantedAuths	//用户的权限
		);
	return userdetail;
}
 
开发者ID:Fetax,项目名称:Fetax-AI,代码行数:20,代码来源:MainUserDetailServiceImpl.java

示例6: accessTokenConverter

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
/**
 * Jwt资源令牌转换器
 * @return accessTokenConverter
 */
@Bean
public JwtAccessTokenConverter accessTokenConverter(){
    return new JwtAccessTokenConverter(){

        /**
         * 重写增强token的方法
         * @param accessToken 资源令牌
         * @param authentication 认证
         * @return 增强的OAuth2AccessToken对象
         */
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

            String userName = authentication.getUserAuthentication().getName();
            User user = (User) authentication.getUserAuthentication().getPrincipal();
            Map<String,Object> infoMap = new HashMap<>();
            infoMap.put("userName",userName);
            infoMap.put("roles",user.getAuthorities());
            ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(infoMap);
            return super.enhance(accessToken, authentication);
        }
    };
}
 
开发者ID:lanshiqin,项目名称:cloud-project,代码行数:28,代码来源:AuthorizationServerConfig.java

示例7: request

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
/**
 * Simulate a request with authenticated user with specified username for a
 * specified duration in nanoseconds.
 *
 * @param username
 *            the username
 * @param durationInNanoseconds
 *            the duration in nanoseconds
 */
protected void request(String username, long durationInNanoseconds) {
	long now = 1510373758000000000L;
	when(registry.getNanos()).thenReturn(now, now + durationInNanoseconds);

	if (username != null) {
		User user = new User(username, "", new ArrayList<GrantedAuthority>());
		Authentication auth = new UsernamePasswordAuthenticationToken(user, null);
		SecurityContextHolder.getContext().setAuthentication(auth);
	}

	try {
		filter.doFilterInternal(mock(HttpServletRequest.class), mock(HttpServletResponse.class),
				mock(FilterChain.class));
	} catch (ServletException | IOException e) {
		e.printStackTrace();
	}
}
 
开发者ID:mevdschee,项目名称:tqdev-metrics,代码行数:27,代码来源:MeasureUserActivityFilterTestBase.java

示例8: userDetailsService

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
@Bean
UserDetailsService userDetailsService() {
    return username -> {
        LOGGER.debug(String.format("Looking for user [%s]", username));
        Account account = accountRepository.findByUsername(username);
        if (account != null) {
            LOGGER.info(String.format("Found user [%s]", username));
            return new User(account.getUsername(), account.getPassword(),
                    true, true, true, true,
                    AuthorityUtils.createAuthorityList("USER"));
        } else {
            LOGGER.info(String.format("Couldn't find user [%s]", username));
            throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username));
        }
    };
}
 
开发者ID:republique-et-canton-de-geneve,项目名称:chvote-protocol-poc,代码行数:17,代码来源:WebSecurityAuthenticationConfigurer.java

示例9: userDetailsService

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
@Bean
public UserDetailsService userDetailsService() {
	return userName -> {
           UserDTO user = userAuthenticationProvider.userService.findByLogin(userName.toLowerCase());
           if (user == null) {
               throw new UsernameNotFoundException(userName);
           }

           Set<SimpleGrantedAuthority> userAuthorities = new HashSet<>();
           List<Role> roles = user.getRoles();
           if (roles != null) {
               for (Role role : roles) {
                   userAuthorities.add(new SimpleGrantedAuthority(role.toString()));
               }
           }

           return new User(userName, userName /* TODO use password */, userAuthorities);
       };
}
 
开发者ID:adessoAG,项目名称:JenkinsHue,代码行数:20,代码来源:SecurityConfiguration.java

示例10: userDetailsService

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
@Bean
public UserDetailsService userDetailsService() {
	return new UserDetailsService() {
		@Override
		public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
			// 通过用户名获取用户信息
			Account account = accountRepository.findByName(name);
			if (account != null) {
				// 创建spring security安全用户
				User user = new User(account.getName(), account.getPassword(),
						AuthorityUtils.createAuthorityList(account.getRoles()));
				return user;
			} else {
				throw new UsernameNotFoundException("用户[" + name + "]不存在");
			}
		}
	};

}
 
开发者ID:leftso,项目名称:demo-spring-boot-security-oauth2,代码行数:20,代码来源:SecurityConfiguration.java

示例11: getAuthentication

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
/**
 * Provide the mock user information to be used
 * 
 * @param withMockOAuth2Token
 * @return
 */
private Authentication getAuthentication(WithMockOAuth2Token withMockOAuth2Token) {
	List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());

	User userPrincipal = new User(withMockOAuth2Token.userName(), withMockOAuth2Token.password(), true, true, true,
			true, authorities);

	HashMap<String, String> details = new HashMap<String, String>();
	details.put("user_name", withMockOAuth2Token.userName());
	details.put("email", "[email protected]");
	details.put("name", "Anil Allewar");

	TestingAuthenticationToken token = new TestingAuthenticationToken(userPrincipal, null, authorities);
	token.setAuthenticated(true);
	token.setDetails(details);

	return token;
}
 
开发者ID:anilallewar,项目名称:microservices-basics-spring-boot,代码行数:24,代码来源:WithOAuth2MockAccessTokenSecurityContextFactory.java

示例12: loadUserDetails

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
protected UserDetails loadUserDetails(Assertion assertion) {
    String username = assertion.getPrincipal().getName();
    if (!StringUtils.hasText(username)) {
        throw new UsernameNotFoundException("Unable to retrieve username from CAS assertion");
    }

    List<GrantedAuthority> authorities = Arrays
            .stream(attributes)
            .map(a -> assertion.getPrincipal().getAttributes().get(a))
            .filter(Objects::nonNull)
            .flatMap(v -> (v instanceof Collection) ? ((Collection<?>) v).stream() : Stream.of(v))
            .map(v -> toUppercase ? v.toString().toUpperCase() : v.toString())
            .map(r -> r.replaceFirst("^ROLE_", ""))
            .map(r -> new SimpleGrantedAuthority("ROLE_" + r))
            .collect(Collectors.toList());

    authorities.addAll(defaultGrantedAuthorities);

    return new User(username, NON_EXISTENT_PASSWORD_VALUE, authorities);
}
 
开发者ID:kakawait,项目名称:cas-security-spring-boot-starter,代码行数:21,代码来源:GrantedAuthoritiesFromAssertionAttributesWithDefaultRolesUserDetailsService.java

示例13: registerGlobalAuthentication

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
@Autowired
public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    LOG.info("Registering global user details service");
    auth.userDetailsService(username -> {
        try {
            BillingUser user = billingDao.loadUser(username);
            return new User(
                    user.getUsername(),
                    user.getPassword(),
                    Collections.singletonList(() -> "AUTH")
            );
        } catch (EmptyResultDataAccessException e) {
            LOG.warn("No such user: " + username);
            throw new UsernameNotFoundException(username);
        }
    });
}
 
开发者ID:izaharkin,项目名称:JavaRestCalculator,代码行数:18,代码来源:SecurityServiceConfiguration.java

示例14: loadUserByUsername

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
public UserDetails loadUserByUsername(String username) {
    SysUser user = userRepository.findByUsername(username);
    if (user != null) {
        List<SysPermission> permissions = permissionRepository.findByAdminUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
        for (SysPermission permission : permissions) {
            if (permission != null && permission.getName()!=null) {

            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
            grantedAuthorities.add(grantedAuthority);
            }
        }
        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
    } else {
        throw new UsernameNotFoundException("admin: " + username + " do not exist!");
    }
}
 
开发者ID:realxujiang,项目名称:itweet-boot,代码行数:18,代码来源:CustomUserService.java

示例15: parseUserFromToken

import org.springframework.security.core.userdetails.User; //导入依赖的package包/类
public User parseUserFromToken(String token) {
    try {
        String username = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        String roleString = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token).getBody().get("roles", String.class);
        List<SimpleGrantedAuthority> roles = new ArrayList<>();
        if (!StringUtils.isEmpty(roleString)) {
            String[] roleValues = StringUtils.split(roleString, ",");
            for (String roleValue : roleValues) {
                roles.add(new SimpleGrantedAuthority(roleValue));
            }
        }
        return new User(username, token, roles);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
        throw new BadCredentialsException("Invalid JWT token: ", ex);
    } catch (ExpiredJwtException expiredEx) {
        throw new JwtExpiredTokenException("JWT Token expired", expiredEx);
    }
}
 
开发者ID:kinota,项目名称:kinota-server,代码行数:25,代码来源:JwtTokenUtil.java


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