【发布时间】:2014-11-19 12:21:05
【问题描述】:
我正在一个使用 spring security 的 spring mvc 项目中工作,我是 spring security 的新手,我想知道如何在我的应用程序中拥有两种类型的用户,一个普通用户和一个管理员用户,并展示一个与管理员用户不同的索引页面和对普通用户具有较少功能的另一个索引页面,到目前为止我有这个:
我的 configSecurity 类 WebSecurityConfigurerAdapter
public class ConfigSecurity extends WebSecurityConfigurerAdapter {
private AutenticarProvider authen;
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http
.authenticationProvider(authen)
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/css/**").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers("/sound/**").permitAll()
.antMatchers("/fonts/**").permitAll()
.antMatchers("/ajax/**").permitAll()
.antMatchers("/php/**").permitAll()
.antMatchers("/xml/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") <-- i am not sure about this just guessing
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/loginPage")
.permitAll()
.and()
.logout()
.permitAll();
}
}
还有我实现 AuthenticationProvider 的类:
@Component
public class AutenthenProvider implements AuthenticationProvider
{
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
User user = null;
Authentication auth = null;
String name = null;
String password = null;
try
{
name = authentication.getName();
password = authentication.getCredentials().toString();
if(name != null && !name.trim().equals("") && password != null && !password.trim().equals(""))
{
user = this.obtainUserFromDataBase(name);
if(user != null)
{
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
auth = new UsernamePasswordAuthenticationToken(name, password);
}
else
{
throw new UsernameNotFoundException("the user dont exist");
}
}
else
{
throw new BadCredentialsException("invalid credentials");
}
}
catch (AuthenticationException e) {
throw e;
}
catch (Exception ex) {
throw new AuthenticationServiceException("", ex.getCause());
}
return auth;
}
和我的控制器类中的控制器方法
@RequestMapping(value = "/loginPage", method = RequestMethod.GET)
public String loginPage(Model model) {
logger.info("**Login PAGE!!**");
return "loginPage";
}
我正在考虑将这一行 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") 放在我的配置方法中,但我不确定它是如何工作的,如果我这样做意味着我将有重复的页面,因为我的应用程序中有页面可以两个用户都可以查看这是否意味着我将这两个页面重复但在不同的文件夹中?
【问题讨论】:
标签: java spring spring-mvc login spring-security