如何在 Spring Security 中获取用户详细信息

x33g5p2x  于2021-10-16 转载在 Spring  
字(1.4k)|赞(0)|评价(0)|浏览(562)

本文将重点介绍如何在 Spring Security 中检索用户详细信息。 要获取当前的登录用户 详细信息,例如用户名和角色,Spring Security 提供 Authentication 接口。

一旦请求被 AuthenticationManagerauthenticate(Authentication *authentication*) 方法处理,它代表身份验证请求或已验证主体的令牌。

让我们跳到编码的实际部分。

1. 创建一些虚拟用户:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("manish")
			.password(passwordEncoder().encode("admin@123")).roles("ADMIN")
			.and()
			.withUser("sandeep")
			.password(passwordEncoder().encode("user@123")).roles("USER");
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}

2. 获取登录用户信息的控制器类:

@RestController
public class UserController {

	@GetMapping("/user")
	public String userInfo(Authentication authentication) {

		String userName = authentication.getName();
		String role = authentication.getAuthorities().stream()
				.findAny().get().getAuthority();

		return "Your user name is: " + userName + " and your role is: " + role;

	}
}

2.1 User authority/role 也可以由用户 Enhanced-For-Loop 检索:

String role = "";
for (GrantedAuthority authority : authentication.getAuthorities()) {
	role = authority.getAuthority();
}

或者,我们也可以使用 getPrincipal() 方法:

UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());

输出:

成功登录后,您将获得当前已登录用户的详细信息,如下所示:

相关文章

微信公众号

最新文章

更多