##如何用安全框架去实现登陆功能?(包含去实现用户名的实现)

安全框架做登陆功能


 我们一般在登陆进入首页之后就会立刻显示账户的用户名等等信息,所以需要我们添加一个ng-init="showName()"的方法

<body class="hold-transition skin-green sidebar-mini" ng-app="pinyougou"
ng-controller="indexController" ng-init="showName()">

然后我们在controller层添加一个方法

package cn.liurui.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liurui
 * @date $ {DATE} 14:45
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @RequestMapping("/showName")
    public Map showName(){
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Map map = new HashMap();
        map.put("username",name);
        return map;
    }
}

因为在页面中获取用户名是通过键值对的方式获取,所以我们这里做了一个map集合,返回一个map集合去获取

,上面这种方式是在安全框架的配置文件种配置的帐户名密码,我们这样获取,那么如果是我们需要访问数据库的情况下,需要怎么做呢?

package cn.liurui.service;

import cn.liurui.core.pojo.seller.Seller;
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 java.util.ArrayList;
import java.util.List;

/**
 * @author liurui
 * @date $ {DATE} 18:46
 */
public class UserDetailServiceImpl implements UserDetailsService{
    private SellerService sellerService;
    public void setSellerService(SellerService sellerService){
        this.sellerService=sellerService;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //首先创建权限
        List<GrantedAuthority> arrayList = new ArrayList<>();
        arrayList.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        //1 获取商家的注册信息
        Seller seller = sellerService.findOne(username);
        if(seller==null){
            return null;
        }
        //判断商家的审核状态是否为1
        if("1".equals(seller.getStatus())){
            return new User(username,seller.getPassword(),arrayList);
        }
        return null;
    }
}

 

posted @ 2019-09-19 09:43  阿锐互联网  阅读(295)  评论(0编辑  收藏  举报