spring boot 實(shí)例之 用戶(hù)登錄

轉(zhuǎn)載請(qǐng)注明出處spring boot 實(shí)例之 用戶(hù)登錄--碧波之心簡(jiǎn)書(shū)

上兩篇完成了用戶(hù)信息表的增刪查,接下來(lái)增加用戶(hù)登錄功能。采用spring security來(lái)進(jìn)行權(quán)限控制。我們希望用戶(hù)可以通過(guò)用戶(hù)名+密碼、郵箱+密碼、手機(jī)號(hào)+驗(yàn)證碼、微信登錄三種登錄途徑。
先用來(lái)完成用戶(hù)名+密碼或手機(jī)號(hào)+驗(yàn)證碼登錄。
前面做的用戶(hù)信息表不是用來(lái)登錄的,那些信息只是用戶(hù)的基本信息。為了在用戶(hù)列表請(qǐng)求得到的數(shù)據(jù)中不包含密碼、手機(jī)號(hào)等敏感信息。把登錄用的數(shù)據(jù)分開(kāi)保存,關(guān)聯(lián)到用戶(hù)信息。

建立對(duì)象

創(chuàng)建數(shù)據(jù)模型 Safety

package com.biboheart.demo.user.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name = "bh_user_safety")
public class Safety {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; // ID
    private Long uid; // 用戶(hù)ID
    private String username; // 用戶(hù)名
    private String mobile; // 手機(jī)號(hào)
    private String password; // 密碼
    private Long createTime; // 創(chuàng)建時(shí)間
    private Long updateTime; // 最后修改時(shí)間
}

創(chuàng)建repository

package com.biboheart.demo.user.repository;

import com.biboheart.demo.user.basejpa.CustomRepository;
import com.biboheart.demo.user.domain.Safety;

public interface SafetyRepository extends CustomRepository<Safety, Long> {
    Safety findByUsernameAndUidNot(String username, Long uid);
    
    Safety findByMobileAndUidNot(String mobile, Long uid);
    
    @Transactional
    void deleteByUid(Long uid);
}

創(chuàng)建service

package com.biboheart.demo.user.service;

import com.biboheart.brick.exception.BhException;
import com.biboheart.demo.user.domain.Safety;

public interface SafetyService {
    public Safety save(Safety safety) throws BhException;
    
    public void delete(Long id, Long uid);
    
    public Safety load(Long uid, String username, String mobile);
}
package com.biboheart.demo.user.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.biboheart.brick.exception.BhException;
import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.brick.utils.TimeUtils;
import com.biboheart.demo.user.domain.Safety;
import com.biboheart.demo.user.repository.SafetyRepository;
import com.biboheart.demo.user.service.SafetyService;

@Service
public class SafetyServiceImpl implements SafetyService {
    @Autowired
    private SafetyRepository safetyRepository;

    @Override
    public Safety save(Safety safety) throws BhException {
        if (null == safety.getId()) {
            safety.setId(0L);
        }
        if (CheckUtils.isEmpty(safety.getUid())) {
            throw new BhException("必須關(guān)聯(lián)到用戶(hù)");
        }
        if (CheckUtils.isEmpty(safety.getUsername())) {
            if (!CheckUtils.isEmpty(safety.getMobile())) {
                safety.setUsername(safety.getMobile());
            }
        }
        if (CheckUtils.isEmpty(safety.getUsername())) {
            throw new BhException("用戶(hù)名不能為空");
        }
        Safety source = safetyRepository.findByUid(safety.getUid());
        if (null != source) {
            safety.setId(source.getId());
        }
        source = safetyRepository.findByUsername(safety.getUsername());
        if (null != source) {
            if (!safety.getUid().equals(source.getUid())) {
                throw new BhException("用戶(hù)名已經(jīng)被占用");
            }
            if (!source.getId().equals(safety.getId())) {
                if (CheckUtils.isEmpty(safety.getId())) {
                    safety.setId(source.getId());
                } else {
                    safetyRepository.deleteById(source.getId());
                }
            }
        }
        source = safetyRepository.findByMobile(safety.getMobile());
        if (null != source) {
            if (!safety.getUid().equals(source.getUid())) {
                throw new BhException("用戶(hù)名已經(jīng)被占用");
            }
            if (!source.getId().equals(safety.getId())) {
                if (CheckUtils.isEmpty(safety.getId())) {
                    safety.setId(source.getId());
                } else {
                    safetyRepository.deleteById(source.getId());
                }
            }
        }
        if (!CheckUtils.isEmpty(safety.getPassword()) && safety.getPassword().length() != 32) {
            safety.setPassword(DigestUtils.md5Hex(safety.getPassword()));
        }
        Long now = TimeUtils.getCurrentTimeInMillis();
        if (CheckUtils.isEmpty(safety.getCreateTime())) {
            safety.setCreateTime(now);
        }
        safety.setUpdateTime(now);
        safety = safetyRepository.save(safety);
        return safety;
    }

    @Override
    public void delete(Long id, Long uid) {
        if (!CheckUtils.isEmpty(uid)) {
            safetyRepository.deleteByUid(uid);
        }
        if (!CheckUtils.isEmpty(id)) {
            safetyRepository.deleteById(id);
        }
    }
    
    @Override
    public Safety load(Long uid, String username, String mobile) {
        Safety safety = null;
        if (!CheckUtils.isEmpty(uid)) {
            safety = safetyRepository.findByUid(uid);
        }
        if (null == safety && !CheckUtils.isEmpty(username)) {
            safety = safetyRepository.findByUsername(username);
        }
        if (null == safety && !CheckUtils.isEmpty(mobile)) {
            safety = safetyRepository.findByMobile(mobile);
        }
        return safety;
    }

}

創(chuàng)建控制器

這里我們先做一個(gè)保存的API,如果不保存一個(gè)密碼的話(huà),登錄的功能不方便測(cè)試。先簡(jiǎn)單的實(shí)現(xiàn)用戶(hù)登錄的功能,接下去再優(yōu)化,修改。把能考慮到的不安全因素解決。

package com.biboheart.demo.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.biboheart.brick.exception.BhException;
import com.biboheart.brick.model.BhResponseResult;
import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.demo.user.domain.Safety;
import com.biboheart.demo.user.domain.User;
import com.biboheart.demo.user.service.SafetyService;
import com.biboheart.demo.user.service.UserService;

@RestController
public class SafetyController {
    @Autowired
    private UserService userService;
    @Autowired
    private SafetyService safetyService;
    
    @RequestMapping(value = "/userapi/safety/save", method = {RequestMethod.POST})
    public BhResponseResult<?> save(Safety safety) throws BhException {
        User user = userService.load(safety.getUid());
        if (null == user) {
            // 如果不是對(duì)某個(gè)用戶(hù)設(shè)置登錄參數(shù)則創(chuàng)建一個(gè)新用戶(hù),用戶(hù)注冊(cè)時(shí)
            user = new User();
            String name = safety.getUsername();
            if (CheckUtils.isEmpty(name)) {
                name = safety.getMobile();
            }
            user.setName(name);
            user = userService.save(user);
        }
        safety.setUid(user.getId());
        safety = safetyService.save(safety);
        return new BhResponseResult<>(0, "success", null != safety);
    }

}

創(chuàng)建一個(gè)用戶(hù)

創(chuàng)建用戶(hù)

用戶(hù)列表

創(chuàng)建一個(gè)用戶(hù)名為biboheart,手機(jī)號(hào)為15000000000,密碼為test的用戶(hù)。用戶(hù)前面的列表接口能查到最新創(chuàng)建的用戶(hù)。

開(kāi)始登錄功能

引入spring security組件,開(kāi)始開(kāi)發(fā)用戶(hù)登錄功能。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

創(chuàng)建包:com.biboheart.demo.user.security,用戶(hù)登錄功能都在這個(gè)包中完成。
創(chuàng)建security配置文件

package com.biboheart.demo.user.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.web.authentication.UsernamePasswordAuthenticationFilter;

import com.biboheart.demo.user.security.filter.BhAuthenticationFilter;
import com.biboheart.demo.user.security.provider.MobileCodeAuthenticationProvider;
import com.biboheart.demo.user.security.provider.UsernamePasswordAuthenticationProvider;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;
    @Autowired
    private MobileCodeAuthenticationProvider mobileCodeAuthenticationProvider;
    
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(mobileCodeAuthenticationProvider)
            .authenticationProvider(usernamePasswordAuthenticationProvider);
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf().disable()
            .addFilterAt(bhAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
                .antMatchers("/", "/home", "/loginIn", "/oauth/authorize", "/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
        // @formatter:on
    }
    
    @Bean
    public BhAuthenticationFilter bhAuthenticationFilter() {
        BhAuthenticationFilter filter = new BhAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManager);
        return filter;
    }
    
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

因?yàn)槲覀冇袃煞N登錄方式,所以我們建立usernamePasswordAuthenticationProvider和mobileCodeAuthenticationProvider兩個(gè)provider來(lái)處理登錄請(qǐng)求。
UsernamePasswordAuthenticationToken是spring security內(nèi)置的token對(duì)象。我們就不再定義了,需要定義一個(gè)MobileCodeAuthenticationToken在包c(diǎn)om.biboheart.demo.user.security.tokens中

package com.biboheart.demo.user.security.tokens;

import java.util.Collection;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

public class MobileCodeAuthenticationToken extends AbstractAuthenticationToken {
    
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    
    private final Object principal;
    private String credentials;

    public MobileCodeAuthenticationToken(Object principal, String credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        setAuthenticated(false);
    }
    
    public MobileCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = null;
        super.setAuthenticated(true); // must use super, as we override
    }

    // ~ Methods
    // ========================================================================================================

    public String getCredentials() {
        return this.credentials;
    }

    public Object getPrincipal() {
        return this.principal;
    }

    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        credentials = null;
    }

}

創(chuàng)建過(guò)濾器

創(chuàng)建一個(gè)過(guò)濾器,替換掉原來(lái)的UsernamePasswordAuthenticationFilter過(guò)濾器。定義為BhAuthenticationFilter 繼承至 AbstractAuthenticationProcessingFilter。

package com.biboheart.demo.user.security.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import com.biboheart.demo.user.security.tokens.MobileCodeAuthenticationToken;

public class BhAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    // ~ Static fields/initializers
    // =====================================================================================

    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    public static final String SPRING_SECURITY_FORM_AUTYPE_KEY = "autype";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private String autypeParameter = SPRING_SECURITY_FORM_AUTYPE_KEY;
    private boolean postOnly = true;

    // ~ Constructors
    // ===================================================================================================

    public BhAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        String autype = obtainAutype(request);
        System.out.println(this.getClass().getName() + "----autype:" + autype);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }
        
        if (autype == null) {
            autype = "";
        }

        username = username.trim();
        
        AbstractAuthenticationToken authRequest = null;
        switch(autype) {
        case "mobileCode":
            authRequest = new MobileCodeAuthenticationToken(username, password);
            break;
        default:
            authRequest = new UsernamePasswordAuthenticationToken(username, password);
            break;
        }

        /*UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);*/

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
    
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(passwordParameter);
    }
    
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(usernameParameter);
    }
    
    protected String obtainAutype(HttpServletRequest request) {
        return request.getParameter(autypeParameter);
    }
    
    protected void setDetails(HttpServletRequest request,
            AbstractAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
    
    public void setAutypeParameter(String autypeParameter) {
        Assert.hasText(autypeParameter, "Autype parameter must not be empty or null");
        this.autypeParameter = autypeParameter;
    }
    
    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }
    
    public void setPasswordParameter(String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }
    
    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return usernameParameter;
    }

    public final String getPasswordParameter() {
        return passwordParameter;
    }

}

對(duì)于登錄請(qǐng)求,我們接收三個(gè)參數(shù)。分別是:username,password,autype。autype參數(shù)用于告知登錄類(lèi)型:默認(rèn)為用戶(hù)名密碼方式,mobileCode為手機(jī)號(hào)驗(yàn)證碼方式。如果是mobileCode方式,那么username對(duì)應(yīng)的是手機(jī)號(hào),password對(duì)應(yīng)的是驗(yàn)證碼。
通過(guò)SecurityConfiguration中的.addFilterAt(bhAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)插入過(guò)濾器。

實(shí)現(xiàn)用戶(hù)認(rèn)證

用戶(hù)名密碼認(rèn)證的實(shí)現(xiàn)

package com.biboheart.demo.user.security.provider;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.demo.user.domain.Safety;
import com.biboheart.demo.user.domain.User;
import com.biboheart.demo.user.service.SafetyService;
import com.biboheart.demo.user.service.UserService;

@Component
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private SafetyService safetyService;
    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
        String password = (String) authentication.getCredentials();
        if (CheckUtils.isEmpty(password)) {
            throw new BadCredentialsException("密碼不能為空");
        }
        Safety safety = safetyService.load(null, username, null);
        if (null == safety) {
            throw new BadCredentialsException("用戶(hù)不存在");
        }
        User user = userService.load(safety.getUid());
        if (null == user) {
            throw new BadCredentialsException("用戶(hù)不存在");
        }
        if (password.length() != 32) {
            password = DigestUtils.md5Hex(password);
        }
        if (!password.equals(safety.getPassword())) {
            throw new BadCredentialsException("用戶(hù)名或密碼不正確");
        }
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(username, password, listUserGrantedAuthorities(user.getId()));
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        System.out.println(this.getClass().getName() + "---supports");
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

    private Set<GrantedAuthority> listUserGrantedAuthorities(Long uid) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if (CheckUtils.isEmpty(uid)) {
            return authorities;
        }
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authorities;
    }

}

手機(jī)號(hào)驗(yàn)證碼認(rèn)證的實(shí)現(xiàn)

package com.biboheart.demo.user.security.provider;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.demo.user.domain.Safety;
import com.biboheart.demo.user.domain.User;
import com.biboheart.demo.user.security.tokens.MobileCodeAuthenticationToken;
import com.biboheart.demo.user.service.SafetyService;
import com.biboheart.demo.user.service.UserService;

@Component
public class MobileCodeAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private SafetyService safetyService;
    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String mobile = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
        String code = (String) authentication.getCredentials();
        if (CheckUtils.isEmpty(code)) {
            throw new BadCredentialsException("驗(yàn)證碼不能為空");
        }
        Safety safety = safetyService.load(null, null, mobile);
        if (null == safety) {
            throw new BadCredentialsException("用戶(hù)不存在");
        }
        User user = userService.load(safety.getUid());
        if (null == user) {
            throw new BadCredentialsException("用戶(hù)不存在");
        }
        // 手機(jī)號(hào)驗(yàn)證碼業(yè)務(wù)還沒(méi)有開(kāi)發(fā),先用4個(gè)0驗(yàn)證
        if (!code.equals("0000")) {
            throw new BadCredentialsException("驗(yàn)證碼不正確");
        }
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(safety.getUsername(), code, listUserGrantedAuthorities(user.getId()));
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        System.out.println(this.getClass().getName() + "---supports");
        return (MobileCodeAuthenticationToken.class.isAssignableFrom(authentication));
    }

    private Set<GrantedAuthority> listUserGrantedAuthorities(Long uid) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if (CheckUtils.isEmpty(uid)) {
            return authorities;
        }
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authorities;
    }

}

更多的認(rèn)證方式照著擴(kuò)展就可以了。

用戶(hù)登錄界面

用戶(hù)登錄需要界面,未登錄時(shí)要跳轉(zhuǎn)到登錄界面,登錄成功后要跳轉(zhuǎn)到首頁(yè)。
頁(yè)面跳轉(zhuǎn)控制器

package com.biboheart.demo.user.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SecurityController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {
        return "login";
    }
}

首頁(yè)控制器

package com.biboheart.demo.user.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {
    
    @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
    public String homePage() {
        return "index";
    }
    
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello";
    }

}

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"></meta>
    <title>Spring Security入門(mén)</title>
</head>
<body>
    <h1>歡迎使用Spring Security!</h1>
    <p>
        點(diǎn)擊 <a href="/hello">這里</a> 打個(gè)招呼吧
    </p>
</body>
</html>

hello.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>Hello World!</title>
</head>
<body>
    <h1>Hello world!</h1>
    <a href="/logout">注銷(xiāo)</a>
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="Sign Out"/>
    </form>
    <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>登錄</title>
</head>
<body>
    <div th:if="${param.containsKey('error')}">
        <p class="error">登錄不成功,可能是用戶(hù)名/密碼錯(cuò)了</p>
    </div>
    <div th:if="${param.containsKey('logout')}">
        <h4>成功 </h4>
        <p>您已經(jīng)成功退出</p>
    </div>
    <form method="post" role="form">
        <div class="form-group">
            用戶(hù)名密碼認(rèn)證 <input name="autype" type="radio" value="usernamePassword" checked="checked"/>
            手機(jī)號(hào)驗(yàn)證碼 <input name="autype" type="radio" value="mobileCode"/>
        </div>
        <div class="form-group">
            <label for="username">用戶(hù)名:</label>
            <input type='text' name='username'/>
        </div>
        <div class="form-group">
            <label for="password">密碼:</label>
            <input type='password' name='password'/>
        </div>
        <!-- <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> -->
        <button class="btn btn-primary" type="submit">登錄</button>
    </form>
    With Github: <a href="/login/github">click here</a>
</body>
</html>

在pom.xml中引入組件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
首頁(yè)

首頁(yè)是允許訪問(wèn)的,點(diǎn)擊“這里”的鏈接。就進(jìn)入登錄頁(yè)面。


登錄界面

選擇手機(jī)號(hào)驗(yàn)證碼登錄:


手機(jī)號(hào)登錄

實(shí)際上這里用戶(hù)和密碼輸入的是手機(jī)號(hào)和驗(yàn)證碼(0000),前端可以控制,根據(jù)不同的選擇改下提示文字。
點(diǎn)擊登錄后進(jìn)入hello頁(yè)面
hello頁(yè)面

可以點(diǎn)擊注銷(xiāo),再試試用戶(hù)名密碼登錄。

總結(jié)

  1. 創(chuàng)建用戶(hù)認(rèn)證的信息對(duì)象;
  2. 引入spring security;
  3. spring security配置文件;
  4. 自定義token;
  5. 自定義provider;
  6. 登錄頁(yè)面
    當(dāng)前目錄結(jié)構(gòu):


    目錄結(jié)構(gòu)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容