gpt4 book ai didi

spring-security - 如何在 spring boot 中获取登录用户名?

转载 作者:行者123 更新时间:2023-12-02 04:50:52 25 4
gpt4 key购买 nike

我正在开发一个带有spring security的spring boot项目,下面是我的安全配置

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource datasource;

@Override
protected void configure(HttpSecurity http) throws Exception {

http
.csrf().disable();


http
.authorizeRequests()
.antMatchers("/ideate","/homecreate").permitAll()
.anyRequest().authenticated();

http
.authorizeRequests().anyRequest().authenticated();
http
.formLogin().failureUrl("/login?error")
.defaultSuccessUrl("/")
.loginPage("/login")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager();

userDetailsService.setDataSource(datasource);
PasswordEncoder encoder = new BCryptPasswordEncoder();

auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
auth.jdbcAuthentication().dataSource(datasource);


}
}

用户成功登录后,我调用写入 Controller 的请求映射“/”,该方法将返回一个页面,该页面应包含用户名作为模型属性我如何获取当前登录的用户名?

最佳答案

在您的 jsp 中使用以下代码 ...

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<sec:authentication property="principal.username" />

这段代码帮助我将用户信息提取到 jsp。

关于spring-security - 如何在 spring boot 中获取登录用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28524126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com