在用户spring中正确登录

tjvv9vkg  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(398)

我尝试在spring中使用以下代码立即登录用户

SecurityContextHolder.getContext().getAuthentication().getName();

我有一个配置类

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private PasswordEncoderConfig passwordEncoderConfig;

@Autowired
public SecurityConfig(PasswordEncoderConfig passwordEncoderConfig) {
    this.passwordEncoderConfig = passwordEncoderConfig;
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    String password = passwordEncoderConfig.passwordEncoder().encode("123");
    String password2 = passwordEncoderConfig.passwordEncoder().encode("456");
    auth.inMemoryAuthentication().withUser("ram").password(password).roles("USER");
    auth.inMemoryAuthentication().withUser("ram1").password(password2).roles("USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic().and()
            .authorizeRequests()
            .antMatchers("/drug/**").anonymous()
            .and().formLogin().permitAll()
                .defaultSuccessUrl("/account/show")
            .and().logout()
            .logoutUrl("/logout")
            .invalidateHttpSession(true)
            .permitAll()
            .and().cors().and().csrf().disable();
}
}

还有一个控制器

@Controller
@RequestMapping(value = "/account")
public class AccountController {

@Autowired
private UserService userService;

@RequestMapping(value = "/show", method = RequestMethod.GET)
public String showAccount(){
    final String currentUserName = SecurityContextHolder.getContext().getAuthentication().getName();
    System.out.println(currentUserName);
    return "account";
}

}

我想在控制器中获取用户名,所以在这种情况下,我想在控制台中打印ram。相反,它一直返回匿名用户,即使我以ram身份登录。我能做些什么来获取用户名?

vecaoik1

vecaoik11#

antmatchers(“/account/**”).authenticated()

相关问题