Spring security中的系统的User只有username,password,enabled等几个属性,对于实际开发中,这些属性用的概率非常低
比如: 用户查看自己的头像,手机号,修改昵称等等, 在spring-security默认的User对象中并不存在这些自定义的字段.怎么办呢?
这就需要我们自己扩展User类了.
思路:
我自己定义的MyUser 继承了spring-security中的User类,对其进行扩展.
- package com.qingcheng.controller;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.userdetails.User;
- import java.util.Collection;
- public class MyUser extends User {
- private Integer id;
- private String loginName;
- private String image;
- public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
- super(username, password, authaorities);
- }
- public MyUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
- super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getLoginName() {
- return loginName;
- }
- public void setLoginName(String loginName) {
- this.loginName = loginName;
- }
- public String getImage() {
- return image;
- }
- public void setImage(String image) {
- this.image = image;
- }
- }
复制代码
然后在UserDetailService的实现类UserDetailServiceImpl中,将匹配到的用户信息, set到自定义的MyUser对象中,再返回,如下:
- package com.qingcheng.controller;
- import com.alibaba.dubbo.config.annotation.Reference;
- import com.qingcheng.pojo.system.Admin;
- import com.qingcheng.service.system.AdminService;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- 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.HashMap;
- import java.util.List;
- import java.util.Map;
- public class UserDetailsServiceImpl implements UserDetailsService {
- @Reference
- private AdminService adminService;
- @Override
- public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
- Map searchMap = new HashMap();
- searchMap.put("loginName",s);
- searchMap.put("status","1");
- List<Admin> list = adminService.findList(searchMap);
- if(list.size() == 0){
- return null;
- }
- ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
- grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
- Admin admin = list.get(0);
- // return new User(s,list.get(0).getPassword(),grantedAuthorities);
- MyUser myUser = new MyUser(s, admin.getPassword(), grantedAuthorities);
- myUser.setId(admin.getId());
- myUser.setLoginName(admin.getLoginName());
- myUser.setImage(admin.getImage());
- return myUser;
- }
- }
复制代码
第一次发帖, 也是java小白, 不要注重于代码,写得比较low.谢谢哈! |
|