Java Code Examples for org.springframework.security.core.authority.AuthorityUtils#createAuthorityList()

The following examples show how to use org.springframework.security.core.authority.AuthorityUtils#createAuthorityList() . 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: EmailServiceImpl.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * Inits the settings.
 */
@PostConstruct
public void initSettings() {
	final Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ADMIN");
	final Authentication authentication = new UsernamePasswordAuthenticationToken("system.init", "n/a", authorities);
	SecurityContextHolder.getContext().setAuthentication(authentication);
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SEND_EMAILS, SEND_EMAIL, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SEND_EMAIL, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SEND_EMAIL, "false"));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_FROM_EMAIL, FROM_EMAIL, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SEND_EMAIL, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_FROM_EMAIL, "[email protected]"));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_HOST, SMTP_HOST, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_HOST, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_HOST, "localhost"));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_PORT, SMTP_PORT, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_PORT, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_PORT, DEFAULT_SMTP_PORT));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_USERNAME, SMTP_USERNAME, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_USERNAME, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_USERNAME, "username"));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_SECRET, SMTP_SECRET, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_SECRET, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_SECRET, "password"));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_AUTH, SMTP_AUTH, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_AUTH, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_AUTH, "true"));
	LOGGER.info(EMAIL_SETTINGS,applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_STARTTLS_ENABLE, SMTP_STARTTLS_ENABLE, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_STARTTLS_ENABLE, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_STARTTLS_ENABLE, "true"));
	SecurityContextHolder.getContext().setAuthentication(null);
}
 
Example 2
Source File: AnonymousAuthenticationFilter.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
public static List<GrantedAuthority> getAuthoritiesUtenzaAnonima() {
	List<GrantedAuthority> authFromPreauth = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
	UserDetails utenzaAnonima = null;
	try {
		AutenticazioneUtenzeAnonimeDAO autenticazioneUtenzeAnonimeDAO = new AutenticazioneUtenzeAnonimeDAO(); 
		autenticazioneUtenzeAnonimeDAO.setApiName("API_PAGAMENTO");
		autenticazioneUtenzeAnonimeDAO.setAuthType("PUBLIC");
		utenzaAnonima = autenticazioneUtenzeAnonimeDAO.loadUserDetails("anonymousUser", authFromPreauth);
	} catch (UsernameNotFoundException e) {
	}
	
	if(utenzaAnonima != null) {
		List<GrantedAuthority> authorities = new ArrayList<>(); 
		authorities.addAll(utenzaAnonima.getAuthorities());
		return authorities;
	}
	
	return AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
}
 
Example 3
Source File: CloudUserDetailsServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 构建userdetails
 *
 * @param result 用户信息
 * @return
 */
private UserDetails getUserDetails(SmakerResult<UserInfo> result) {
	if (result == null || result.getData() == null) {
		throw new UsernameNotFoundException("用户不存在");
	}

	UserInfo info = result.getData();
	Set<String> dbAuthsSet = new HashSet<>();
	if (ArrayUtil.isNotEmpty(info.getRoles())) {
		// 获取角色
		Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
		// 获取资源
		dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

	}
	Collection<? extends GrantedAuthority> authorities
		= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
	SysUser user = info.getSysUser();

	// 构造security用户
	return new CloudUser(user.getUserId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),
		StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), true, true, true, authorities);
}
 
Example 4
Source File: AbstractHazelcastIndexedSessionRepositoryITests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void createSessionWithSecurityContextAndFindByPrincipal() {
	Assumptions.assumeTrue(this.hazelcastInstance instanceof HazelcastInstanceProxy,
			"Hazelcast runs in embedded server topology");

	HazelcastSession session = this.repository.createSession();

	String username = "saves-" + System.currentTimeMillis();
	Authentication authentication = new UsernamePasswordAuthenticationToken(username, "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
	securityContext.setAuthentication(authentication);
	session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext);

	this.repository.save(session);

	assertThat(this.repository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username))
					.hasSize(1);
}
 
Example 5
Source File: WebSocketAuthenticationManager.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
public HiveAuthentication authenticateAnonymous(HiveAuthentication.HiveAuthDetails details) {
    AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken(
            UUID.randomUUID().toString(), "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
    HiveAuthentication authentication = (HiveAuthentication) authenticationManager.authenticate(authenticationToken);
    authentication.setDetails(details);
    return authentication;
}
 
Example 6
Source File: JdbcSecurityConfiguration.java    From pro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public UserDetailsService userDetailsService(JdbcTemplate jdbcTemplate) {
	RowMapper<User> userRowMapper = (ResultSet rs, int i) ->
		new User(
			rs.getString("ACCOUNT_NAME"),
			rs.getString("PASSWORD"),
			rs.getBoolean("ENABLED"),
			rs.getBoolean("ENABLED"),
			rs.getBoolean("ENABLED"), 
			rs.getBoolean("ENABLED"),
			AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
	return username ->
		jdbcTemplate.queryForObject("SELECT * from ACCOUNT where ACCOUNT_NAME = ?",
				userRowMapper, username);
}
 
Example 7
Source File: JdbcSecurityConfiguration.java    From pro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public UserDetailsService userDetailsService(JdbcTemplate jdbcTemplate) {
	RowMapper<User> userRowMapper = (ResultSet rs, int i) ->
		new User(
			rs.getString("ACCOUNT_NAME"),
			rs.getString("PASSWORD"),
			rs.getBoolean("ENABLED"),
			rs.getBoolean("ENABLED"),
			rs.getBoolean("ENABLED"), 
			rs.getBoolean("ENABLED"),
			AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
	return username ->
		jdbcTemplate.queryForObject("SELECT * from ACCOUNT where ACCOUNT_NAME = ?",
				userRowMapper, username);
}
 
Example 8
Source File: AuthenticationConfiguration.java    From java-microservice with MIT License 5 votes vote down vote up
@Bean
protected UserDetailsService userDetailsService() {
    return (email) -> {
        com.apssouza.pojos.User user = userService.getUserByEmail(email);
        return new User(
                user.getEmail(),
                user.getPassword(),
                true, true, true, true,
                AuthorityUtils.createAuthorityList("USER", "write")
        );
    };
}
 
Example 9
Source File: JdbcSecurityConfiguration.java    From pro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean
public UserDetailsService userDetailsService(JdbcTemplate jdbcTemplate) {
	RowMapper<User> userRowMapper = (ResultSet rs, int i) ->
		new User(
			rs.getString("ACCOUNT_NAME"),
			rs.getString("PASSWORD"),
			rs.getBoolean("ENABLED"),
			rs.getBoolean("ENABLED"),
			rs.getBoolean("ENABLED"), 
			rs.getBoolean("ENABLED"),
			AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
	return username ->
		jdbcTemplate.queryForObject("SELECT * from ACCOUNT where ACCOUNT_NAME = ?",
				userRowMapper, username);
}
 
Example 10
Source File: MockMvcTests.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Test
public void indexWhenAuthenticationThenOk() throws Exception {
	UserDetails user = new User("user", "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	Authentication auth = new UsernamePasswordAuthenticationToken(user,
			user.getPassword(), user.getAuthorities());
	MockHttpServletRequestBuilder request = get("/").accept(MediaType.TEXT_HTML)
			.with(authentication(auth));
	this.mockMvc.perform(request).andExpect(status().isOk());
}
 
Example 11
Source File: UserDaoRealm.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
@Override
protected UserDetails getLoginUser(String loginId) {
    User user = null;
    List<GrantedAuthority> authorityList = null;

    try {
        // login_idをメールアドレスと見立てる
        val criteria = new UserCriteria();
        criteria.setEmail(loginId);

        // ユーザーを取得して、セッションに保存する
        user = userDao.select(criteria)
                .orElseThrow(() -> new UsernameNotFoundException("no user found. [id=" + loginId + "]"));

        // 担当者権限を取得する
        List<UserRole> userRoles = userRoleDao.selectByUserId(user.getId(), toList());

        // 役割キーにプレフィックスをつけてまとめる
        Set<String> roleKeys = userRoles.stream().map(UserRole::getRoleKey).collect(toSet());

        // 権限キーをまとめる
        Set<String> permissionKeys = userRoles.stream().map(UserRole::getPermissionKey).collect(toSet());

        // 役割と権限を両方ともGrantedAuthorityとして渡す
        Set<String> authorities = new HashSet<>();
        authorities.addAll(roleKeys);
        authorities.addAll(permissionKeys);
        authorityList = AuthorityUtils.createAuthorityList(authorities.toArray(new String[0]));

    } catch (Exception e) {
        // 0件例外がスローされた場合は何もしない
        // それ以外の例外は、認証エラーの例外で包む
        if (!(e instanceof NoResultException)) {
            throw new UsernameNotFoundException("could not select user.", e);
        }
    }

    return new LoginUser(user, authorityList);
}
 
Example 12
Source File: LoginController.java    From microservices-event-sourcing with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    httpSessionSecurityContextRepository.loadContext(holder);

    try {
        // 使用提供的证书认证用户
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");
        Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth));

        // 认证用户
        if(!auth.isAuthenticated())
            throw new CredentialException("用户不能够被认证");
    } catch (Exception ex) {
        // 用户不能够被认证,重定向回登录页
        logger.info(ex);
        return "login";
    }

    // 从会话得到默认保存的请求
    DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    // 为令牌请求生成认证参数Map
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    model.addAttribute("authorizationRequest", authRequest);

    httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
    return "authorize";
}
 
Example 13
Source File: UserDetailsServiceImpl.java    From cloud-template with MIT License 5 votes vote down vote up
/**
 * 构造包含用户信息的UserDetails对象。本项目仅提供用户信息,其他数据模拟
 * 应该包括:用户信息、角色信息、权限信息,这些数据都应该从数据库中查询。
 *
 * @param result
 * @return
 */
private UserDetails getUserDetails(Result<SysUser> result) {
    if (result == null || result.getData() == null) {
        throw new UsernameNotFoundException("用户不存在");
    }
    SysUser user = result.getData();

    // 模拟构造包含用户角色列表的`List<GrantedAuthority>`对象
    List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ADMIN");

    return new SctUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true, authorityList);
}
 
Example 14
Source File: StaffDaoRealm.java    From spring-boot-doma2-sample with Apache License 2.0 4 votes vote down vote up
@Override
protected UserDetails getLoginUser(String email) {
    Staff staff = null;
    List<GrantedAuthority> authorityList = null;

    try {
        // login_idをメールアドレスと見立てる
        val criteria = new StaffCriteria();
        criteria.setEmail(email);

        // 担当者を取得して、セッションに保存する
        staff = staffDao.select(criteria)
                .orElseThrow(() -> new UsernameNotFoundException("no staff found [id=" + email + "]"));

        // 担当者権限を取得する
        List<StaffRole> staffRoles = staffRoleDao.selectByStaffId(staff.getId(), toList());

        // 役割キーにプレフィックスをつけてまとめる
        Set<String> roleKeys = staffRoles.stream().map(StaffRole::getRoleKey).collect(toSet());

        // 権限キーをまとめる
        Set<String> permissionKeys = staffRoles.stream().map(StaffRole::getPermissionKey).collect(toSet());

        // 役割と権限を両方ともGrantedAuthorityとして渡す
        Set<String> authorities = new HashSet<>();
        authorities.addAll(roleKeys);
        authorities.addAll(permissionKeys);
        authorityList = AuthorityUtils.createAuthorityList(authorities.toArray(new String[0]));

        return new LoginStaff(staff, authorityList);

    } catch (Exception e) {
        if (!(e instanceof UsernameNotFoundException)) {
            // 入力間違い以外の例外はログ出力する
            log.error("failed to getLoginUser. ", e);
            throw e;
        }

        // 0件例外がスローされた場合は何もしない
        // それ以外の例外は、認証エラーの例外で包む
        throw new UsernameNotFoundException("could not select staff.", e);
    }
}
 
Example 15
Source File: LoginController.java    From cloud-native-microservice-strangler-example with GNU General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {

    HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
    sessionRepository.loadContext(responseHolder);

    try {
        // Authenticate the user with the supplied credentials
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");

        Authentication auth =
                new UsernamePasswordAuthenticationToken(request.getParameter("username"),
                        request.getParameter("password"), authorities);

        SecurityContextHolder.getContext()
                .setAuthentication(authenticationManager.authenticate(auth));

        // Authenticate the user
        if(!authenticationManager.authenticate(auth).isAuthenticated())
            throw new CredentialException("User could not be authenticated");

    } catch (Exception ex) {
        // The user couldn't be authenticated, redirect back to login
        ex.printStackTrace();
        return "login";
    }

    // Get the default saved request from session
    DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));

    // Generate an authorization parameter map for the token request
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);

    // Create the authorization request and put it in the view model
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clients).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
    model.addAttribute("authorizationRequest", authRequest);

    // Return the token authorization view
    return "authorize";
}
 
Example 16
Source File: KerberosUserDetailsService.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return new User(username, "notUsed", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER"));
}
 
Example 17
Source File: RedisIndexedSessionRepositoryITests.java    From spring-session with Apache License 2.0 4 votes vote down vote up
@Test
void saves() throws InterruptedException {
	String username = "saves-" + System.currentTimeMillis();

	String usernameSessionKey = "RedisIndexedSessionRepositoryITests:index:" + INDEX_NAME + ":" + username;

	RedisSession toSave = this.repository.createSession();
	String expectedAttributeName = "a";
	String expectedAttributeValue = "b";
	toSave.setAttribute(expectedAttributeName, expectedAttributeValue);
	Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext();
	toSaveContext.setAuthentication(toSaveToken);
	toSave.setAttribute(SPRING_SECURITY_CONTEXT, toSaveContext);
	toSave.setAttribute(INDEX_NAME, username);
	this.registry.clear();

	this.repository.save(toSave);

	assertThat(this.registry.receivedEvent(toSave.getId())).isTrue();
	assertThat(this.registry.<SessionCreatedEvent>getEvent(toSave.getId())).isInstanceOf(SessionCreatedEvent.class);
	assertThat(this.redis.boundSetOps(usernameSessionKey).members()).contains(toSave.getId());

	Session session = this.repository.findById(toSave.getId());

	assertThat(session.getId()).isEqualTo(toSave.getId());
	assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames());
	assertThat(session.<String>getAttribute(expectedAttributeName))
			.isEqualTo(toSave.getAttribute(expectedAttributeName));

	this.registry.clear();

	this.repository.deleteById(toSave.getId());

	assertThat(this.repository.findById(toSave.getId())).isNull();
	assertThat(this.registry.<SessionDestroyedEvent>getEvent(toSave.getId()))
			.isInstanceOf(SessionDestroyedEvent.class);
	assertThat(this.redis.boundSetOps(usernameSessionKey).members()).doesNotContain(toSave.getId());

	assertThat(this.registry.getEvent(toSave.getId()).getSession().<String>getAttribute(expectedAttributeName))
			.isEqualTo(expectedAttributeValue);
}
 
Example 18
Source File: AlternateKerberosUserDetailsService.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return new User(username, "notUsed", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER"));
}
 
Example 19
Source File: UserRepositoryUserDetailsService.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
	return AuthorityUtils.createAuthorityList("ROLE_USER");
}
 
Example 20
Source File: DefaultCalendarService.java    From Spring-Security-Third-Edition with MIT License 4 votes vote down vote up
public int createUser(CalendarUser user) {
    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    UserDetails userDetails = new User(user.getEmail(), user.getPassword(), authorities);
    userDetailsManager.createUser(userDetails);
    return userDao.createUser(user);
}