【发布时间】:2014-09-14 18:41:46
【问题描述】:
我正在研究 JAVA EE 技术来学习 JSF-Spring-Hibernate 与... 我正在尝试使用不同的用户角色来做 Web 应用程序。现在,我只有一个用户角色 ROLE_USER。我无法改变那个角色。我尝试了调试模式以了解我们如何设置此角色,但我不明白它发生在哪里。
所以,我的主要问题是我无法在我的应用程序中创建任何其他角色。如果我在我的流程中不使用<secured attributes="ROLE_USER" />(我使用的是spring web-flow),每个人都可以访问该页面。如果我只做 ROLE_USER。但我想创建名为 ROLE_ADMIN 的新角色,只让 ROLE_ADMIN 到达该页面。
注意:我没有在这里添加所有文件,因为有人跟我说只添加相关的类和文件。如果您需要更多信息,请告诉我。
这是我正在关注的教程源代码。 https://code.google.com/p/jee-tutorial-youtube/source/browse/
安全配置.xml
<?xml version="1.0" encoding="UTF-8"?>
<security:http auto-config="true">
<security:form-login login-page="/app/main"
default-target-url="/app/account" />
<security:logout logout-url="/app/logout"
logout-success-url="/app/main" />
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="userServiceImp">
<security:password-encoder hash="md5" />
</security:authentication-provider>
</security:authentication-manager>
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userServiceImp" />
<property name="hideUserNotFoundExceptions" value="false" />
</bean>
<bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<ref bean="daoAuthenticationProvider" />
</constructor-arg>
</bean>
这是我对用户进行身份验证的 UserAuthenticationProviderServiceImp 类。
public boolean processUserAuthentication(Users user) {
try {
Authentication request = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
return true;
} catch(AuthenticationException e) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "Sorry!"));
return false;
}
}
我发现这个函数,我的服务类,在 processUserAuthentication 中被调用。然后我认为这是设置角色的函数。
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
Users user = userDao.loadUserByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException(String.format(
getMessageBundle().getString("badCredentials"), userName));
}
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("USER_ROLE"));
User userDetails = new User(user.getUserName(), user.getPassword(),
authorities);
return userDetails;
}
更新:
在我的项目中,我必须使用以下语法来创建角色:ROLE_X 其中 x 是任何字符串。例子;我们可以有 ROLE_MYNAME 但我们不能有 MYNAME 或 MYNAME_ROLE 作为角色。它必须以 ROLE_ 开头。我仍在尝试找出导致此问题的原因。如果我找到任何答案,我会更新。
编辑: 在这个页面中有一个详细的解释为什么我们必须使用ROLE_; http://bluefoot.info/howtos/spring-security-adding-a-custom-role-prefix/
【问题讨论】:
标签: spring authentication spring-security roles spring-webflow-2