编程知识 cdmana.com

Spring security pit entry (II)

Memory based verification was implemented last time Lack of actual availability, now modify SpringSecurity To achieve basic database validation

pom.xml Dependency please refer to SpringSecurity Into the pit ( One ) The specific dependencies are not modified here

Verify based on database , The main thing is Build permission verification Nonsense XX Go straight up CODE

User User table , be based on SpringDataJpa structure User User table

package com.shaojie.authority.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;

import javax.persistence.*;

/**
 * @author ShaoJie
 * @Date 2019 year 11 month 25 17:49
 * @Description:
 */
@Data
@Entity
@AllArgsConstructor
@Accessors(chain = true)
@Table(name = "user")
public class User {

    /**
     *  Self increase of users  id
     */
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /**
     *  User's account 
     */
    @Column(name = "name")
    private String name;

    /**
     *  User's password 
     */
    @Column(name = "password")
    private String password;

    /**
     *  Whether the account is enabled 
     */
    @Column(name = "enable")
    private Boolean enable;

    public User() {

    }

}

Authority Permissions on the table Save user permissions

package com.shaojie.authority.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;

import javax.persistence.*;

/**
 * @author: ShaoJie
 * @data: 2020 year 01 month 06 Japan  20:22
 * @Description:  User's rights 
 */
@Data
@Entity
@AllArgsConstructor
@Accessors(chain = true)
@Table(name = "authority")
public class Authority {

    /**
     *  Self increase of users  id
     */
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /**
     *  User's account 
     */
    @Column(name = "member_id")
    private Integer memberId;

    /**
     *  User's rights 
     */
    @Column(name = "authority")
    private String authority;

    public Authority() {

    }
}

User Data access layer

package com.shaojie.authority.dao;

import com.shaojie.authority.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author ShaoJie
 * @Date 2019 year 11 month 25 18:46
 * @Description:
 */
public interface UserRepository extends JpaRepository<User, Integer> {
    /**
     *  Query the user according to the user's account 
     *
     * @param name  User's account 
     * @return  User information 
     */
    User findUserByName(String name);
}

User Business logic layer of

package com.shaojie.authority.service;

import com.shaojie.authority.model.User;

/**
 * @author ShaoJie
 * @Date 2019 year 11 month 25 18:49
 * @Description:
 */
public interface UserService {

    /**
     *  Query the user according to the user's account 
     *
     * @param name  User's account 
     * @return  User information 
     */
    User findUserByName(String name);

}

Authority Business logic layer of

package com.shaojie.authority.dao;

import com.shaojie.authority.model.Authority;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author: ShaoJie
 * @data: 2020 year 01 month 06 Japan  21:10
 * @Description:  jurisdiction   Data access layer 
 */
public interface AuthorityRepository extends JpaRepository<Authority, Integer> {
}

Authority Business logic layer of

package com.shaojie.authority.service;

import com.shaojie.authority.model.Authority;

import java.util.List;

/**
 * @author: ShaoJie
 * @data: 2020 year 01 month 06 Japan  21:14
 * @Description:  Business logic layer of permission 
 */
public interface AuthorityService {

    /**
     *  Get user permissions 
     *
     * @param memberId  User  id
     * @return  Set of authorities 
     */
    List<Authority> getUserAuthority(Integer memberId);
}

Authority Business logic of impl layer

package com.shaojie.authority.service.impl;

import com.shaojie.authority.dao.AuthorityRepository;
import com.shaojie.authority.model.Authority;
import com.shaojie.authority.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: ShaoJie
 * @data: 2020 year 01 month 06 Japan  21:14
 * @Description:  Business logic layer of permission 
 */
@Service
@Transactional
public class AuthorityServiceImpl implements AuthorityService {

    /**
     *  Permission data access layer 
     */
    @Autowired
    private AuthorityRepository authorityRepository;

    /**
     *  Get user permissions 
     *
     * @param memberId  User  id
     * @return  Set of authorities 
     */
    @Override
    public List<Authority> getUserAuthority(Integer memberId) {
        Example<Authority> example = Example.of(new Authority()
                .setMemberId(memberId));
        return authorityRepository.findAll(example);
    }
}

User Business logic of impl layer

package com.shaojie.authority.security;

import com.shaojie.authority.model.Authority;
import com.shaojie.authority.model.User;
import com.shaojie.authority.service.UserService;
import com.shaojie.authority.service.impl.AuthorityServiceImpl;
import lombok.extern.slf4j.Slf4j;
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.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ShaoJie
 * @Date 2019 year 11 month 26 19:48
 * @Description:
 */
@Service
@Transactional
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     *  user   Business logic layer 
     */
    @Autowired
    private UserService userService;

    /**
     *  jurisdiction   Business logic layer 
     */
    @Autowired
    private AuthorityServiceImpl authorityService;

    /**
     *  Password encryption 
     */
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     *  Load login   Search for users by user name 
     *
     * @param userName  Login user name 
     * @return  User information 
     * @throws UsernameNotFoundException  User login name information not found 
     */
    @Transactional(readOnly = true)
    @Override
    public UserDetails loadUserByUsername(@RequestParam String userName) throws UsernameNotFoundException {
        log.info("{  Currently logged in user account :  {} }", userName);
        User user = userService.findUserByName(userName);
        List<GrantedAuthority> authorityList =  new ArrayList<>();
        if (user != null) {
            //  Privilege set   Permissions of the current user 
            authorityList = getUserAuthority(user.getId());
        }
        return new org.springframework.security.core.userdetails.User(user.getName(), bCryptPasswordEncoder.encode(user.getPassword()), authorityList);
    }

    /**
     *  Connect to database   Realization   Read permission set 
     *
     * @return  Authority granted 
     */
    public List<GrantedAuthority> getUserAuthority(Integer memberId) {
        //  Create permission set 
        List<GrantedAuthority> authorityList = new ArrayList<>();
        //  Read the user's permission set 
        List<Authority> userAuthority = authorityService.getUserAuthority(memberId);
        for (Authority a : userAuthority) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(a.getAuthority());
            authorityList.add(grantedAuthority);
        }
        return authorityList;
    }

}

I wrote it all directly here , There is no subdivision , In fact, this stratification should not be like this , This is just a basic presentation , So maybe the code is a little rough , Be interested in making adjustments by yourself , Here is the key step , That's it Build permission verification

Build permission verification

package com.shaojie.authority.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author ShaoJie
 * @Date 2019/10/25
 */
@Configuration
//  start-up  SpringSecurity  The filter chain 
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *  Password encryption 
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

    /**
     *  User details   Business logic layer 
     */
    @Autowired
    public UserDetailsServiceImpl userDetailsService;

    /**
     *  to grant authorization 
     *
     * @param auth
     * @throws Exception
     */
    //  Instead of the configuration file  <security:authentication-manager></security:authentication-manager>
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //  be based on   Database validation 
        auth.userDetailsService(userDetailsService());
    }

    /**
     *  verification 
     *
     * @param http
     * @throws Exception
     */
    //  Instead of the configuration file  <security:http></security:http>
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // antMatchers  Set blocked requests   hasAnyAuthority  Corresponding permission name 
                // .hasAnyAuthority("PRODUCT_ADD")  The permissions of the user 
                .antMatchers("/product/add").hasAnyAuthority("PRODUCT_ADD")
                .antMatchers("/product/update").hasAnyAuthority("PRODUCT_UPDATE")
                .antMatchers("/product/list").hasAnyAuthority("PRODUCT_LIST")
                .antMatchers("/product/delete").hasAnyAuthority("PRODUCT_DELETE")
                // permitAll  All permissions can access 
                .antMatchers("/login").permitAll()
//                .antMatchers("/**")
                // fullyAuthenticated  Anonymous users are not allowed to view 
//                .fullyAuthenticated()
                //  Set that all requests must be authenticated to access 
                .anyRequest().authenticated()
                .and()
                // httpbasic  Sign in 
                // .httpBasic();
                //  Form login 
                .formLogin()
                //   Log in to the requested page 
                .loginPage("/login")
                //  Handling login requests   Address 
                .loginProcessingUrl("/index")
                //  modify  spring  Provided   Default login parameters 
                .usernameParameter("userName")
                .passwordParameter("password")
                .and()
                //  Turn on remember me 
                .rememberMe()
                .and()
                //  Enable logout 
                .logout()
                .and()
                //  Disable cross domain protection 
                .csrf().disable();

    }
}

Here's the thing to note Permission here , Now just First do write dead permission , What permissions does the system have , Here, you need to configure... In the database , Continue to sort out later , And the main thing is , You need to configure the to handle login requests Address , Based on the previous chapter SpringSecurity Into the pit ( One ) The page needs to be modified :

login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2> The login page </h2>
    <form th:action="@{/index}" method="post">
         account number :<input type="text" name="userName" value="1591313226@163.com"><br>
         password :<input type="password" name="password" value="123456"><br>
        <button type="submit"> Sign in </button>
    </form>
</body>
</html>

It should be noted that , Submitted here method Must be post

To this basic access database , Operation authority verification , That's it ,SpringSecurity It provides a lot of , We learn slowly , Try to absorb this well . There's still a long way to go , Need to touch slowly , Don't worry too much

I haven't studied for a long time , A lot of things are getting rusty , Make progress together , Limited ability , Share as much as you can learn , Step by step , Step a little , Now life is average , uncomfortable , Eat more bitter , The New Year , Come on

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Shao Jie]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183600836A.html

Scroll to Top