管理系统类毕设(五)---简单鉴权认证实现

奥里给 到家了
方便区分用户权限
区分教务处老师和普通老师权限

加入依赖

在这里插入图片描述

编写一个用户类

继承UserDetails类
在这里插入图片描述

@Entity
public class User implements UserDetails {
    
    


    /**
     * 编号
     */
    @Id
    @GeneratedValue
    private Integer userId;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 权限
     */
    private String roles;

    /**
     * 验证码
     * 未使用
     */
    private Integer lastvcode;

    public Integer getUserId() {
    
    
        return userId;
    }

    public void setUserId(Integer userId) {
    
    
        this.userId = userId;
    }

    @Override
    public boolean isAccountNonExpired() {
    
    
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
    
    
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
    
    
        return true;
    }

    @Override
    public boolean isEnabled() {
    
    
        return true;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
    
    
        return null;
    }

    @Override
    public String getPassword() {
    
    
        return password;
    }

    @Override
    public String getUsername() {
    
    
        return username;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    public Integer getLastvcode() {
    
    
        return lastvcode;
    }

    public void setLastvcode(Integer lastvcode) {
    
    
        this.lastvcode = lastvcode;
    }

    public String getRoles() {
    
    
        return roles;
    }

    public void setRoles(String roles) {
    
    
        this.roles = roles;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "userId=" + userId +
                ", username='" + username + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return
                Objects.equals(username, user.username) ;
    }

    @Override
    public int hashCode() {
    
    
        return Objects.hash(username);
    }
}

配置用户数据库操作

@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
    
    


    Optional<User> findByUsername(String username);

}

配置登陆时查询数据库操作

方便认证鉴权使用

@Service
public class UserService implements UserDetailsService {
    
    


    @Autowired
    UserRepository userRepository;

//    @Autowired
//    PasswordEncoder passwordEncoder;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
    

        Optional<User> optionalUser = userRepository.findByUsername(username);
            User user;
            if (!optionalUser.isPresent()){
    
    
                throw new UsernameNotFoundException("用户不存在");
            }
            user = optionalUser.get();

            List<GrantedAuthority> authorityList = new ArrayList<>();
            if (user.getRoles().equals("user")) {
    
    

                authorityList.add(new SimpleGrantedAuthority("ROLE_user"));

            }

            if (user.getRoles().equals("admin")) {
    
    

                authorityList.add(new SimpleGrantedAuthority("ROLE_admin"));

            }



            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    authorityList
            );
    }
}

配置Security

编写Security配置类 继承WebSecurityConfigurerAdapter
CTRL加鼠标左键可以看源码
在这里插入图片描述

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    

    @Autowired
    UserService userService;

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
    
    
        return super.authenticationManager();
    }

    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
    
    
        return userService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.userDetailsService(userDetailsService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http
                .antMatcher("oauth/**")
                .authorizeRequests()
               .and()
                .sessionManagement().maximumSessions(1)
                .and()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .antMatchers("/logout").permitAll()
                .and().cors().and().csrf().disable()

                ;
    }
}

配置资源管理类

说明
系统一共配置两种权限
管理员和普通用户
管理员可以操作全部操作 普通用户只能查成绩啥的

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
    
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    
    
        resources.resourceId("rid").stateless(true);
    }



    @Override
    public void configure(HttpSecurity http) throws Exception {
    
    

        http
                .authorizeRequests()
                .antMatchers("/sign").permitAll()
                .antMatchers("/logout").permitAll()
                .antMatchers("/admin/**").hasAnyRole("admin")
                .antMatchers("/user/**").hasAnyRole("user","admin")
                .anyRequest().authenticated()
                .and()
                .cors();
    }
}

配置鉴权

@Configuration
@EnableAuthorizationServer
public class AuthorizationSeverConfig extends AuthorizationServerConfigurerAdapter {
    
    


    @Autowired
    AuthenticationManager authenticationManager;

//	  @Autowired 如果使用redis请使用这个 并注释 DataSource
//    且endpoints.tokenStore(new JdbcTokenStore(dataSource))替换为endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
//    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    UserDetailsService userService;

    @Autowired
    DataSource dataSource;

    @Bean
    PasswordEncoder passwordEncoder(){
    
    
        return new BCryptPasswordEncoder();//加密
    }



    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    
    
        clients.inMemory()
                .withClient("password")
                .authorizedGrantTypes("password","refresh_token")//密码登陆认证
                .accessTokenValiditySeconds(18000)//有效时间
                .resourceIds("rid")//资源id看资源配置类
                .scopes("all")
                .secret(passwordEncoder().encode("123"));

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    
    
        endpoints.tokenStore(new JdbcTokenStore(dataSource))
                .authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    
    
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }
}

建立数据库表

DROP TABLE IF EXISTS `oauth_access_token`;
CREATE TABLE `oauth_access_token` (
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `token_id` varchar(255) DEFAULT NULL,
  `token` blob,
  `authentication_id` varchar(255) DEFAULT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `client_id` varchar(255) DEFAULT NULL,
  `authentication` blob,
  `refresh_token` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `oauth_refresh_token`;
CREATE TABLE `oauth_refresh_token` (
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `token_id` varchar(255) DEFAULT NULL,
  `token` blob,
  `authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

测试

获取访问令牌

在这里插入图片描述

获取用户信息

在这里插入图片描述

文章有点水 抱歉 刚到家 不太想写 哈哈







  大家好,我是代码哈士奇,是一名软件学院网络工程的学生,因为我是“狗”,狗走千里吃肉。想把大学期间学的东西和大家分享,和大家一起进步。但由于水平有限,博客中难免会有一些错误出现,有纰漏之处恳请各位大佬不吝赐教!暂时只在csdn这一个平台进行更新,博客主页:https://blog.csdn.net/qq_42027681

未经本人允许,禁止转载

在这里插入图片描述


后续会推出

前端:vue入门 vue开发小程序 等
后端: java入门 springboot入门等
服务器:mysql入门 服务器简单指令 云服务器运行项目
python:推荐不温卜火 一定要看哦
一些插件的使用等

大学之道亦在自身,努力学习,热血青春
如果对编程感兴趣可以加入我们的qq群一起交流:974178910
在这里插入图片描述

有问题可以下方留言,看到了会回复哦

猜你喜欢

转载自blog.csdn.net/qq_42027681/article/details/112643755
今日推荐