Configuration file for spring security security framework

Posted by LanceT on Sat, 07 Sep 2019 08:25:02 +0200

Here I write the configuration files for two different spring security security frameworks:
1. Use users in memory
2. Users in the database

1. Users in memory:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">

    <!--
       Unfiltered resources (static resources and login-related)
      Another non-intercept resource configuration: <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
      IS_AUTHENTICATED_ANONYMOUSLY means no interception
   -->
    <security:http security="none" pattern="/login.html" />
    <security:http security="none" pattern="/failure.html" />
    <!-- 
	auto-config="false" uses its own login page, and does not use the framework to provide default login pages    
    	use-expressions="false" requires expression to write permissions
    -->
    <security:http auto-config="true" use-expressions="false">
        <! -- Configuration data connection, indicating that any path requires ROLE_USER privileges - >
        <security:intercept-url pattern="/**" access="ROLE_USER" />
        <! - Custom login page:
        login-page Custom Logging Page
        login-processing-url access path
        Name submitted from username-parameter page
        Password submitted from password-parameter page
        authentication-failure-url user rights verification fails before jumping to this page.
                                    If there is no such user in the database, it will not jump to this page.
        default-target-url page to jump after successful login.
        Note: The login page user name is fixed: username, password: password, action: login - >.
        <security:form-login login-page="/login.html"
                             login-processing-url="/login" username-parameter="username"
                             password-parameter="password" authentication-failure-url="/failer.html"
                             default-target-url="/success.html"
        />
        <!--
            Sign out
            invalidate-session deletes session
            logout-url: logout-success-url: exit success page
            Note: Exit operation can log out the current user only by linking to logout
        -->
        <security:logout invalidate-session="true" logout-url="/logout"
                         logout-success-url="/login.jsp" />
        <! - Close CSRF, the defau lt is to open the closed anti-theft chain - >.
        <security:csrf disabled="true" />
    </security:http>
    <! - Store usernames and passwords in memory - >
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="user" password="{noop}user"
                               authorities="ROLE_USER" />
                <security:user name="admin" password="{noop}admin"
                               authorities="ROLE_ADMIN" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

2. Use users in the database (need to implement UserDetails Service:

When using spring security, the spring security framework replaces the controller layer

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- Configuration of non-intercepted resources -->
    <security:http pattern="/login.jsp" security="none"/>
    <security:http pattern="/failure.jsp" security="none"/>
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>

    <!--
       //Configure specific rules
       auto-config="true"     Instead of writing your own login page, the framework provides the default login page
       use-expressions="false"    Whether to use SPEL Expression
    -->
    <security:http auto-config="false" use-expressions="false">
        <!-- Configure specific interception rules pattern="Rules for Request Path" access="Visitors to the system must have ROLE_USER Role" -->
        <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>

        <!-- Define specific pages for jumps -->
        <!--login-page Pages accessed
            login-processing-url Access Path
            default-target-url Log in successfully jumped pages
            authentication-failure-url Pages with insufficient permissions to jump-->
        <security:form-login
                login-page="/login.jsp"
                login-processing-url="/login"
                default-target-url="/index.jsp"
                authentication-failure-url="/failure.jsp"
        />

        <!-- Close cross-domain request anti-theft chain-->
        <security:csrf disabled="true"/>

        <!--
            //Sign out
            invalidate-session Whether to delete session
            logout-url: Logout Processing Link logout-success-url: Exit success page (page that jumps after exit)
            //Note: Exit operation can log out the current user only by linking to logout
        -->
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />

    </security:http>

    <!-- Switch to username and password in database -->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userService">
            <!-- How to configure encryption -->
            <!--<security:password-encoder ref="passwordEncoder"/>-->
        </security:authentication-provider>
    </security:authentication-manager>

    <!-- Configure encryption classes -->
    <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
</beans>

service layer:

The interface of service layer:

package cn.kgc.rentCar.service;

import org.springframework.security.core.userdetails.UserDetailsService;

public interface RootService extends UserDetailsService {

}

(2) Implementation Class of service Layer

package cn.kgc.rentCar.service.impl;

import cn.kgc.rentCar.dao.RootDao;
import cn.kgc.rentCar.pojo.RootUser;
import cn.kgc.rentCar.service.RootService;
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.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

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

@Service("userService")
public class RootServiceImpl implements RootService {
    @Autowired
    RootDao rootDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        RootUser rootUser = rootDao.findByUsername(username);
        User user = new User(rootUser.getUsername(),"{noop}"+rootUser.getPassword(),getAuthority());
        return user;
    }

    private List<SimpleGrantedAuthority> getAuthority() {
        ArrayList<SimpleGrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("ROLE_USER"));
        return list;
    }
}

dao layer:

package cn.kgc.rentCar.dao;

import cn.kgc.rentCar.pojo.RootUser;
import org.apache.ibatis.annotations.Select;

public interface RootDao {
    @Select("select * from root where username=#{username}")
    RootUser findByUsername(String username);
}

over~

Topics: JSP Spring Session Database