spring security 入门(1)

原创
2019/05/12 13:15
阅读数 31

最后的项目结构:

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
</parent>

<groupId>com.mdtech.security</groupId>
<artifactId>md-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>md-security</name>
<description>spring security学习</description>

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

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

  <dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  </dependency>

  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
  </dependency>
</dependencies>

UserController.ajava

package com.mdtech.security.demo.modules.user.controller;

import com.mdtech.security.demo.modules.user.model.User;
import com.mdtech.security.demo.modules.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author calebzhao<9 3 9 3 4 7 5 0 7 @ qq.com>
 * 2019/5/11 15:55
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("查询用户详情")
    @GetMapping("/get")
    public User getUserById(long id){
        User user = userService.getUserById(id);
        return user;
    }
}

BrowserSecurityConfig.java

package com.mdtech.security.borwser.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author calebzhao
 * @date 2019/5/10 16:55
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                    .anyRequest().permitAll();

        http
                .formLogin()
                    .loginPage("/login.html")
                    .loginProcessingUrl("/user/login")
                .and()
                .authorizeRequests()
                    .antMatchers("/login.html").permitAll()
                    .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

}

AuthenticateUserDetailService.java

package com.mdtech.security.borwser.authentication;

import com.mdtech.security.borwser.model.Address;
import com.mdtech.security.borwser.model.UserModel;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author calebzhao<9 3 9 3 4 7 5 0 7 @ qq.com>
 * 2019/5/11 20:47
 */
@Component
public class AuthenticateUserDetailService implements UserDetailsService {

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    private List<UserModel> userModelList = new ArrayList<>();

    public AuthenticateUserDetailService(){
        UserModel userModel = new UserModel();
        userModel.setId(1L);
        userModel.setNickname("zhangsan");
        userModel.setUsername("calebzhao");
        userModel.setPassword("123");
        userModel.setBirthday(new Date());

        Address address1 = new Address();
        address1.setId(1);
        address1.setProvinceId("111");
        address1.setCityId("222");
        address1.setDistrictId("333");

        Address address2 = new Address();
        address2.setId(2);
        address2.setProvinceId("1112");
        address2.setCityId("2222");
        address2.setDistrictId("3333");

        List addressList = new ArrayList<>(2);
        addressList.add(address1);
        addressList.add(address2);

        userModel.setAddressList(addressList);

        userModelList.add(userModel);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Optional<UserModel> userOptional = this.userModelList.stream().filter(item -> item.getUsername().equals(s)).findFirst();

        if (!userOptional.isPresent()){
            return null;
        }

        UserModel userModel = userOptional.get();
        User user = new User(s, userModel.getPassword(), AuthorityUtils.createAuthorityList("admin"));
        return user;
    }
}

登录页面 src\main\resources\resources\login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>标准登录</title>
</head>
<body>
    <h2>登录</h2>
    <form action="/user/login" method="post">
        <div>
            <label for="username">用户名:</label>
            <div>
                <input type="text" name="username" maxlength="16" id="username"/>
            </div>
        </div>
        <div>
            <label for="password">密码:</label>
            <div>
                <input type="password" name="password" maxlength="16" id="password"/>
            </div>
        </div>

        <input type="submit" value="登录">
    </form>
</body>
</html>

application.yml

server:
  port: 7070

spring:
  profiles:
    active: @spring.profiles.active@
  application:
    name: md-security-demo

访问localhosy:7070

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部