如何在登录页面上添加角色?

时间:2016-04-15 19:12:37

标签: spring java-ee

我使用Spring和webflow创建登录页面,但我不知道如何导入数据库表的值并将其放在我的程序中以控制用户角色的访问。这是我的一些代码。 security-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security.xsd">


        <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="userServices">
                <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="userServices" />
            <property name="hideUserNotFoundExceptions" value="false" />
        </bean>

        <bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
            <constructor-arg>
                <ref  bean="daoAuthenticationProvider" />
            </constructor-arg>
        </bean>
</beans>

这是我的account-flow.xml

<?xml version="1.0" encoding="UTF-8"?>
<flow xmlns="http://www.springframework.org/schema/webflow"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/webflow
        http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">

    <secured attributes="ROLE_USER"/>

    <view-state id="home" view="accountHome.xhtml">
    </view-state>

</flow>

我加载用户的方法

public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        UserEntity user = userDao.loadUserByUserName(userName);

        if(user == null){
            throw new UsernameNotFoundException(String.format("Etulisateur introuvable '%s'", userName)); 
        }

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        User userDetails = new User(user.getUserName(), user.getPassWord(), authorities);

        return userDetails;
    }

0 个答案:

没有答案