Complete design of management system (5)---implementation of simple authentication

Ori’s got home. It’s
easy to distinguish user permissions and
distinguish the permissions of teachers in the Academic Affairs Office and ordinary teachers.

Add dependency

Insert picture description here

Write a user class

Inherit the UserDetails class
Insert picture description here

@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);
    }
}

Configure user database operations

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


    Optional<User> findByUsername(String username);

}

Configure query database operation during login

Convenient for authentication and authentication

@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
            );
    }
}

Configure Security

Write the Security configuration class inherit WebSecurityConfigurerAdapter
CTRL plus the left mouse button to see the source code
Insert picture description here

@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()

                ;
    }
}

Configure resource management class

Note The
system is configured with two kinds of permissions,
administrator and ordinary user. The
administrator can operate all operations. Ordinary users can only check the results.

@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();
    }
}

Configure authentication

@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();
    }
}

Create a database table

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;

test

Get access token

Insert picture description here

Get user information

Insert picture description here

The article is a bit watery, sorry I didn't want to write when I just got home haha







  Hello, everyone, I am a code husky, a student of network engineering in the Software College, because I am a "dog", and I can eat meat for thousands of miles. I want to share what I learned during university and make progress with everyone. However, due to the limited level, there will inevitably be some mistakes in the blog. If there are any omissions, please let me know! For the time being, only update on the csdn platform, the blog homepage: https://blog.csdn.net/qq_42027681 .

未经本人允许,禁止转载

Insert picture description here


Will be launched later

Front-end: vue entry vue development applet, etc.
Back-end: java entry springboot entry, etc.
Server: MySQL entry server simple instructions cloud server to run the project
python: recommended not to warm up, be sure to see
the use of some plug-ins, etc.

The way of university is also in oneself, study hard, youth
with passion. If you are interested in programming, you can join our qq group to communicate together: 974178910
Insert picture description here

If you have any questions, you can leave a message below, I will reply if you see it

Guess you like

Origin blog.csdn.net/qq_42027681/article/details/112643755