Java中使用Spring security(二)

作者: 傻姑不傻 | 来源:发表于2020-08-06 20:30 被阅读0次

    上一篇,我们讲述的spring security的基础使用。但是对于一些复杂权限场景,我们需要更高级一些的功能。

    我们接着往下展示它的高级部分。

    <security:authentication-manager>的内部高级设置

    在上一篇的Spring security设置示例中,我设置了authentication-manager来检查登录用户凭证,并使用<user-service>标签中定义的纯文本用户。如下所示,您可以在此处为您的应用程序定义多个用户。

    <security:user-service>
        <security:user name="stiti" password="mindfire" authorities="USER" />
        <security:user name="ram" password="pass1234" authorities="ADMIN" />
        .
        .
        and so on...
    </security:user-service>
    

    上面的方式,是简单的校验。对于更复杂的,比如要对数据库中的Users表进行身份验证,则可以使用<security:jdbc-user-service>替换<security:user-service> ... </ security:user-service>标记。如下。

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service 
    
                data-source-ref="dataSource"  
    
                users-by-username-query=
                    "SELECT username, password FROM users WHERE username=? AND active=1" 
    
                authorities-by-username-query=
                    "SELECT US.username, UR.authority 
                        FROM users US, user_roles UR 
                        WHERE US.user_id = UR.user_id and US.username =?" 
    
                />
        </security:authentication-provider>
    </security:authentication-manager>
    

    在这里,您执行SQL查询以从数据库中的“users”表中获取用户名和密码。

    类似地,用户名的授权权限也从“user_roles”数据库表中获取。

    在这里您可以注意到我在“data-source-ref”属性中提到了数据源引用。这是“dataSource”。

    因此,您需要在应用程序Context xml文件中定义一个id =“dataSource”的Bean。如下。

    <beans ....>
    ...
    ...
    ...
        <!-- Datasource Config -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driverClassName}"></property>
            <property name="url" value="${jdbc.databaseurl}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>
    ...
    ...
    </beans>
    

    我在上面的数据库属性标记的“value”中提供了占位符。您可以用实际值替换它们。

    如果要通过数据访问对象层(DAO)@Service对数据库中的Users表进行身份验证,则可以按如下方式进行配置。

    <security:authentication-manager>
        <security:authentication-provider user-service-ref="loginService">
        </security:authentication-provider>
    </security:authentication-manager>
    

    在这里,您执行SQL查询以从数据库中的“users”表中获取用户名和密码。

    类似地,用户名的授权权限也从“user_roles”数据库表中获取。

    在这里您可以注意到我在<security:authentication-provider>标记中提到了user-service-ref =“loginService”

    spring安全性将使用名为“loginService”的存储库服务获取身份验证。

    我们可以为我们的登录服务创建数据访问对象接口和实现。

    比如:我们创建一个名为“LoginDAO.java”的接口java类

    package com.stiti.dao;
    
    import com.stiti.model.AppUser;
    
    public interface LoginDAO {
    
        Object findUserByUsername(String username);
    
    }
    

    com.stiti.model.AppUserAppUserRole是Model类。

    您可以使用自己的方式获取数据库用户和用户角色表并定义 findUserByUsername(String username)函数体。

    findUserByUsername(String username)返回AppUser类型对象。

    package com.stiti.dao.impl;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.HibernateException;
    
    import org.springframework.stereotype.Repository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.stiti.dao.LoginDAO;
    import com.stiti.model.AppUser;
    import com.stiti.model.AppUserRole;
    
    /**
     * @author Stiti Samantray
     */
    @Repository("loginDao")
    @Transactional
    public class LoginDAOImpl implements LoginDAO {
    
        @Autowired
        SessionFactory sessionFactory;
    
    
        /**
         * Finds the AppUser which has a matching username
         * @param username
         * @return
         */
        @Override
        public AppUser findUserByUsername( String username )
        {
            Session session = sessionFactory.getCurrentSession();
    
            List<AppUser> users = new ArrayList<AppUser>();
            List<Object> userData = new ArrayList<Object>();
            Set<AppUserRole> userRoles = new HashSet<AppUserRole>(0);
    
            try {
                String hql = "FROM AppUser U WHERE U.username = :username";
                org.hibernate.Query query = session.createQuery(hql)
                        .setParameter("username", username);
                users = query.list();
            } catch (HibernateException e) {
                System.err.println("ERROR: "+ e.getMessage());
            }
    
            AppUser user = null;
    
            if(users.size() > 0) {
                user = (AppUser) users.get(0);
    
                // Get the user roles
                try {
                    String hql = "FROM AppUserRole R WHERE R.username = :username";
    
                    org.hibernate.Query query = session.createQuery(hql)
                            .setParameter("username", username);
    
                    userRoles = new HashSet<AppUserRole>(query.list());
                } catch (HibernateException e) {
                    // You can log the error here. Or print to console
                }
    
                user.setUserRole(userRoles);
            }
    
            return user;
    
        }
    }
    

    findUserByUsername(String username) 返回AppUser类型对象。

    package com.stiti.service;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    
    import org.springframework.stereotype.Service;
    
    import com.stiti.model.AppUser;
    import com.stiti.model.AppUserRole;
    import com.stiti.dao.LoginDAO;
    
    /**
     * This class gets the appuser information from the database and 
     * populates the "org.springframework.security.core.userdetails.User" type object for appuser.
     *
     * @author Stiti Samantray
     */
    @Service("loginService")
    public class LoginServiceImpl implements UserDetailsService {
    
        @Autowired
        private LoginDAO loginDao;
    
    
        /**
         * @see UserDetailsService#loadUserByUsername(String)
         */
        @Override
        public UserDetails loadUserByUsername( String username ) throws UsernameNotFoundException
        {
            AppUser user = (AppUser) loginDao.findUserByUsername(username);        
            List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
            return buildUserForAuthentication(user, authorities);
        }
    
    
        private List<GrantedAuthority> buildUserAuthority(Set<AppUserRole> appUserRole) {
            Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
            // Build user's authorities
            for (AppUserRole userRole : appUserRole) {
                System.out.println("****" + userRole.getUserRole());
                setAuths.add(new SimpleGrantedAuthority(userRole.getUserRole()));
            }
            List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
            return Result;
        }
    
    
        private User buildUserForAuthentication(AppUser user, List<GrantedAuthority> authorities) {
            return new User(user.getUsername(), user.getPassword(), true, true, true, true, authorities);
        }
    
    }
    

    编写Spring MVC应用程序的Controller

    现在我们需要编写Spring MVC应用程序的Controller。

    我们需要在Controller类中为应用程序的主路径定义一个RequestMapping方法,该路径在我的示例“/”中。当用户打开应用程序URL例如“http://www.example.com/”时,执行为该请求映射定义的以下方法“loadHomePage()”。在此方法中,它首先获得对此URL的用户身份验证和授权。

    Spring-security将首先检查spring配置中的<security:intercept_url>,以查找允许访问此url路径的角色。在此示例中,它查找允许具有角色“USER”的用户访问此URL路径。如果用户有一个角色= USER,那么它将加载主页。

    否则,如果它是匿名用户,则spring安全校验会将它重定向到登录页面。

    package com.stiti.controller;
    
    import java.util.HashSet;
    import java.util.Set;
    import org.springframework.security.authentication.AnonymousAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.SessionAttributes;
    
    @Controller
    @SessionAttributes(value={"accountname"}, types={String.class})
    public class HomeController {
    
        @SuppressWarnings("unchecked")
        @RequestMapping(value="/", method = RequestMethod.GET)
        public String executeSecurityAndLoadHomePage(ModelMap model) {
    
            String name = null;
            Set<GrantedAuthority> role = new HashSet<GrantedAuthority>();
    
            //check if user is login
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (!(auth instanceof AnonymousAuthenticationToken)) {
                // Get the user details
                UserDetails userDetail = (UserDetails) auth.getPrincipal();
                name = userDetail.getUsername();
                role = (Set<GrantedAuthority>) userDetail.getAuthorities();
            }
    
            // set the model attributes
            model.addAttribute("accountname", name);
            model.addAttribute("userRole", role);
    
            // go to Home page
            return "Home";
    
        }
    
    }
    

    在我们的Controller类中定义RequestMapping方法以加载自定义“登录页面”,前提是您在Spring <security:http> <security:form-login ...>标记中提到了自定义登录页面URL。否则无需为Login页面定义任何控制器方法,spring会自动将用户带到spring-security的默认登录表单页面,这是一个由spring-security本身编写的简单JSP页面。

    // Show Login Form
    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String login(ModelMap model, 
            @RequestParam(value="error",defaultValue="") String error) {
    
        // If fails to login
        if (!error.isEmpty()){
            model.addAttribute("error", "true");
        }
    
        return "Login";
    
    }
    

    在我们的Controller类中为spring-security config中<security:logout>标记中定义的“logout-success-url”定义一个方法。对于此示例,我将“logout-success-url”定义为“/ logout”。

    // Logout page
    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logout(ModelMap model) {
    
        return "Login";
    
    }
    

    在Login.jsp中写入Login表单

    现在让我们看一下登录表单中Login.jsp应包含的内容。

    <form name='login_form' action="<c:url value='j_spring_security_check' />" method='POST'>
        <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='username' value=''></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='password' /></td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit" value="submit" /></td>
            </tr>
            <tr>
                <td colspan='2'><input name="reset" type="reset" /></td>
            </tr>
        </table>
    </form>
    

    结论

    为了在应用程序中实现安全性,开发人员必须在他的应用程序中执行很多操作。Spring安全性通过简化方法来替代所有这些开销。它很容易插入应用程序,Spring安全本身可以处理应用程序的所有安全方面,并为您的应用程序提供严格的安全性。

    思考:

    authentication-manager有几种方式来校验用户名/密码?

    答:

    至少有三种,

    security:user配置固定的用户名/密码方式,最简单;

    jdbc-user-service 配置sql语句校验方式

    user-service-ref配置service bean进行校验,此方式自定义扩展

    相关文章

      网友评论

        本文标题:Java中使用Spring security(二)

        本文链接:https://www.haomeiwen.com/subject/unvtdktx.html