- Spring Security国际化配置:
要实现Spring Security的国际化,需要进行以下配置:
(1)在Spring Security的配置文件中增加MessageSourceBean的配置,并将其注入到Spring Security的配置中:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MessageSource messageSource;
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**","/css/**","/js/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
@Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH);
cookieLocaleResolver.setCookieName("language");
cookieLocaleResolver.setCookieMaxAge(3600);
return cookieLocaleResolver;
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
SavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler = new SavedRequestAwareAuthenticationSuccessHandler();
authenticationSuccessHandler.setTargetUrlParameter("targetUrl");
return authenticationSuccessHandler;
}
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
SimpleUrlAuthenticationFailureHandler authenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler();
authenticationFailureHandler.setUseForward(true);
authenticationFailureHandler.setDefaultFailureUrl("/login?error");
return authenticationFailureHandler;
}
}
(2)在项目的资源文件中增加messages.properties和messages_zh_CN.properties两个文件,分别用于英语和中文语言环境的国际化支持。
messages.properties
login.title=Login Page
login.username=Username
login.password=Password
login.signIn=Sign in
login.language=Language
home.title=Home Page
home.welcome=Welcome, {0}!
403.title=Access Denied
403.message=Sorry, you do not have permission to access this page.
messages_zh_CN.properties
login.title=登录页
login.username=用户名
login.password=密码
login.signIn=登录
login.language=语言
home.title=主页
home.welcome=欢迎,{0}!
403.title=拒绝访问
403.message=对不起,你没有权限访问这个页面。
(3)在页面中添加语言环境的切换按钮,并实现其功能,即控制语言环境参数的传递。
<div class="language-switch">
<a href="?language=en">English</a>
<span>|</span>
<a href="?language=zh_CN">中文</a>
</div>
- UserCache的配置和使用:
UserCache主要用于在一个会话中缓存用户信息,主要配置如下:
(1)在Spring Security的配置文件中增加UserCacheBean的配置,并将其注入到Spring Security的配置中:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserCache userCache;
@Bean
public UserCache userCache() {
return new HttpSessionUserCache();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.successHandler(authenticationSuccessHandler())
.failureHandler(authenticationFailureHandler())
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf().disable();
}
}
(2)在登录成功后,通过UserCache缓存用户信息:
@Service
public class AuthenticationUserDetailsService implements UserDetailsService {
@Autowired
private UserCache userCache;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 查数据库获取用户信息
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
String password = user.getPassword();
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
UserDetails userDetails = new User(username, password, authorities);
userCache.putUserInCache(userDetails);
return userDetails;
}
}
(3)在需要使用UserCache缓存的地方,通过UserCache获取缓存的用户信息:
@Controller
public class HomeController {
@Autowired
private UserCache userCache;
@GetMapping("/home")
public String home(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
UserDetails userDetails = userCache.getUserFromCache(username);
String welcomeMessage = messageSource().getMessage("home.welcome", new Object[]{userDetails.getUsername()}, LocaleContextHolder.getLocale());
model.addAttribute("welcomeMessage", welcomeMessage);
return "home";
}
}
在以上代码中,我们通过UserCache缓存登录成功后的用户信息,在HomeController中的home方法中,通过UserCache获取缓存的用户信息,然后从国际化的资源文件中获取欢迎信息,并添加到model中。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:spring security国际化及UserCache的配置和使用 - Python技术站