我使用了 2 个登录页面,一个用于用户,另一个用于管理员。但是我已经将管理员信息存储在内存中,但已从数据库中获取用户信息。这里的问题是,当我想使用身份验证对象时,它会返回 null。但是SecurityContextHolder给了我完美的价值。我想全局设置此身份验证值,以便我的每个方法都可以拥有它。
这是我的安全配置类
// admin login class
@Configuration
@Order(1)
public class AdminAuthorization extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasRole("ADMIN").and().formLogin()
.loginPage("/adminLogin").loginProcessingUrl("/admin/dashboard").and().csrf().disable();
}
// for authentication
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password(encoder().encode("admin")).roles("ADMIN");
}
}
// Publisher login class
@Configuration
@Order(2)
public class PublisherAuthorization extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
try {
http.authorizeRequests()
.antMatchers("/publisher/**").hasRole("PUBLISHER")
.and().formLogin().loginPage("/login")
.loginProcessingUrl("/login").successForwardUrl("/publisher/welcome")
.failureUrl("/login?error").usernameParameter("username").passwordParameter("password");
} catch (Exception e) {
e.printStackTrace();
}
}
// for authentication
@Autowired
public void configure(AuthenticationManagerBuilder auth) {
try {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, active" + " from publisher where username=?")
.passwordEncoder(encoder())
.authoritiesByUsernameQuery("select username, authority " + "from authorities where username=?");
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Bean
public static PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
首页控制器
@PostMapping(value = { "/welcome", "/welcome/{QuestionPageNumber}/{ArticlePageNumber}" })
public ModelAndView page(Authentication auth, @PathVariable Optional<Integer> QuestionPageNumber,
@PathVariable Optional<Integer> ArticlePageNumber) {
System.out.println(auth==null); //returns true
//but
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println(authentication.getName()); //returns correct user's information
现在,问题是,我不使用此代码
SecurityContextHolder.getContext((.getAuthentication((;
在每一行上。我不知道原因!! 我无法收集发布商的信息。管理员工作正常。
尝试以下代码而不是内存身份验证实现:
import org.springframework.security.core.userdetails.User;
String username = "ADMIN";
String encodedPassword = new BCryptPasswordEncoder().encode("admin");
List<SimpleGrantedAuthority> authList = Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
User user = new User(username, encodedPassword, authList);
auth.inMemoryAuthentication().withUser(user);