【大牛疯狂教学】Java中使用Spring-security(二)

<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();
# 最后

无论是哪家公司,都很重视基础,大厂更加重视技术的深度和广度,面试是一个双向选择的过程,不要抱着畏惧的心态去面试,不利于自己的发挥。同时看中的应该不止薪资,还要看你是不是真的喜欢这家公司,是不是能真的得到锻炼。

针对以上面试技术点,我在这里也做一些资料分享,希望能更好的帮助到大家。

**[戳这里免费领取以下资料](https://gitee.com/vip204888/java-p7)**

![](https://img-blog.csdnimg.cn/img_convert/150001a528f86f16b83ffe4476a5adf8.png)

![](https://img-blog.csdnimg.cn/img_convert/878bfec40cc8a7fdae4380374dca3e72.png)

![](https://img-blog.csdnimg.cn/img_convert/b5c927eb5d91d4729166aeedc4a7c10c.png)

炼。

针对以上面试技术点,我在这里也做一些资料分享,希望能更好的帮助到大家。

**[戳这里免费领取以下资料](https://gitee.com/vip204888/java-p7)**

[外链图片转存中...(img-WoKXHKi3-1628081598884)]

[外链图片转存中...(img-MBUUKJwr-1628081598887)]

[外链图片转存中...(img-LQwGfKFY-1628081598888)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值