iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >SpringCloud的spring-security怎么配置
  • 739
分享到

SpringCloud的spring-security怎么配置

2023-06-05 04:06:37 739人浏览 薄情痞子
摘要

这篇文章主要讲解了“SpringCloud的spring-security怎么配置”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SprinGCloud的spring-security怎么配置

这篇文章主要讲解了“SpringCloudspring-security怎么配置”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SprinGCloud的spring-security怎么配置”吧!

一、简介

WEB应用的安全管理,主要包括两个方面的内容:身份认证、用户授权,此处使用spring-cloud-security来说明。

二、依赖管理

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-security</artifactId></dependency><dependency>   <groupId>org.thymeleaf.extras</groupId>   <artifactId>thymeleaf-extras-springsecurity4</artifactId></dependency>

三、安全策略配置

Spring Security已经大体实现了,我们这里只是需要一些配置与引用。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

package com.example.demo.config;

 

import com.example.demo.utils.security.CustomUserService;

import com.example.demo.utils.security.LoginSuccesshandler;

import com.example.demo.utils.security.MyFilterSecurityInterceptor;

import com.example.demo.utils.security.SecuritySettings;

import org.apache.commons.lang3.StringUtils;

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.web.builders.httpsecurity;

import org.springframework.security.config.annotation.web.builders.WebSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

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

import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

 

@Configuration

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 

    @Autowired

    private CustomFilterSecurityInterceptor customFilterSecurityInterceptor;    // 权限管理过滤器

    @Autowired

    private SecuritySettings securitySettings;     // 自定义安全配置类

 

    

    @Bean

    public UserDetailsService customUserService(){

        return new CustomUserService();

    }

 

    

    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(customUserService()); //userDetailsService验证

 

    }

 

    

    @Override

    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/js

    @Override

    protected void configure(HttpSecurity http) throws Exception {

        // 设置游客可以访问的URI

        if (StringUtils.isNotBlank(securitySettings.getPermitall())) {

            http.authorizeRequests().antMatchers(securitySettings.getPermitall().split(",")).permitAll();

        }

 

        http.authorizeRequests()

                .anyRequest().authenticated() //任何请求,登录后可以访问

                // 配置登录URI、登录失败跳转URI与登录成功后默认跳转URI

                .and().fORMLogin().loginPage("/login").failureUrl("/login?error").permitAll().defaultSuccessUrl("/"true).successHandler(loginSuccessHandler())

                // 注销行为任意访问

                .and().loGout().permitAll()

                // 设置拒绝访问的提示URI

                .and().exceptionHandling().accessDeniedPage("/login?illegal")

        ;

 

        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);

    }

 

    

    private AuthenticationSuccessHandler loginSuccessHandler() {

        return new LoginSuccessHandler();

    }

}

说明:

 loginPage:设置一个实验自定义的登录URI

 loginSuccessHandler:设置自定义的登录处理器

 permitAll:是允许访问

 accessDeniedPage:配置拒绝访问的提示URI

 antMatchers:对URI的配置

了解springcloud架构可以加求求:三五三六二四七二五九

假设我要管理员才可以访问admin文件夹下的内容,如:.antMatchers("/admin

@Configuration

@ConfigurationProperties(prefix = "securityConfig")

public class SecuritySettings {

    

    private String permitall;

 

    public String getPermitall() {

        return permitall;

    }

 

    public void setPermitall(String permitall) {

        this.permitall = permitall;

    }

}

2、登录成功处理器

登录成功后,如果需要对用户的行为做一些记录或者执行其它操作,则可以使用登录成功处理器。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package com.example.demo.utils.security;

 

import com.example.demo.pojo.SysUser;

import org.springframework.security.core.Authentication;

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

import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

 

public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Override

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        User userDetails = (User) authentication.getPrincipal();

        System.out.println("登录用户:username=" + userDetails.getUsername() + ", uri=" + request.getContextPath());

        super.onAuthenticationSuccess(request, response, authentication);

    }

}

3、springMVC 配置(访问 /login 转向 login.html 页面)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package com.example.demo.config;

 

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ViewControllerReGIStry;

import org.springframework.web.servlet.config.annotation.WebmvcConfigurerAdapter;

 

@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter {

 

    @Override

    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/login").setViewName("login");

    }

}

四、登录认证

在安全策略配置代码中有,主要看自定义的CustomUserService,此类实现了UserDetailsService接口,重写了loadUserByUsername方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

package com.example.demo.utils.security;

 

import com.example.demo.dao.SysPermissionDao;

import com.example.demo.dao.SysUserDao;

import com.example.demo.pojo.SysPermission;

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

import com.example.demo.pojo.SysUser;

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 java.util.ArrayList;

import java.util.List;

 

public class CustomUserService implements UserDetailsService {

    @Autowired

    private SysUserDao sysUserDao;

    @Autowired

    private SysPermissionDao sysPermissionDao;

 

    @Override

    public UserDetails loadUserByUsername(String username) {

        SysUser user = sysUserDao.findByUserName(username);

        if (user != null) {

            List<SysPermission> permissions = sysPermissionDao.findByAdminUserId(user.getId());

            List<GrantedAuthority> grantedAuthorities = new ArrayList <>();

            for (SysPermission permission : permissions) {

                if (permission != null && permission.getName()!=null) {

                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());

                    //1:此处将权限信息添加到 GrantedAuthority 对象中,在后面进行全权限验证时会使用GrantedAuthority 对象。

                    grantedAuthorities.add(grantedAuthority);

                }

            }

            return new User(user.getUsername(), user.getPassword(), grantedAuthorities);

        else {

            throw new UsernameNotFoundException("admin: " + username + " do not exist!");

        }

    }

}

五、权限管理

在Security安全配置类中使用了权限管理过滤器CustomFilterSecurityInterceptor

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

package com.example.demo.utils.security;

 

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.access.SecurityMetadataSource;

import org.springframework.security.access.intercept.AbstractSecurityInterceptor;

import org.springframework.security.access.intercept.InterceptorStatusToken;

import org.springframework.security.web.FilterInvocation;

import org.springframework.stereotype.Service;

 

import java.io.IOException;

 

@Service

public class CustomFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {

    @Autowired

    private CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;  // 权限配置资源管理器

 

    

    @Autowired

    public void setMyAccessDecisionManager(CustoMaccessDecisionManager customAccessDecisionManager) {

        super.setAccessDecisionManager(customAccessDecisionManager);

    }

  

    @Override

    public void init(FilterConfig filterConfig) throws ServletException {

 

    }

 

    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

 

        FilterInvocation fi = new FilterInvocation(request, response, chain);

        invoke(fi);

    }

  

    public void invoke(FilterInvocation fi) throws IOException, ServletException {

        //fi里面有一个被拦截的url

        //里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限

        //再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够

        InterceptorStatusToken token = super.beforeInvocation(fi);

        try {

            //执行下一个拦截器

            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());

        finally {

            super.afterInvocation(token, null);

        }

    }

 

    @Override

    public void destroy() {

 

    }

 

    @Override

    public Class<?> getSecureObjectClass() {

        return FilterInvocation.class;

    }

 

    @Override

    public SecurityMetadataSource obtainSecurityMetadataSource() {

        return this.customFilterInvocationSecurityMetadataSource;

    }

}

说明:

 customFilterSecurityInterceptor:权限管理过滤器

 customAccessDecisionManager:权限管理决断器

 customFilterInvocationSecurityMetadataSource:权限配置资源管理器

其中过滤器在系统启动时开始工作,并同时导入权限配置资源管理器和权限管理决断器,对用户访问的资源进行管理。权限管理决断器对用户访问的资源与用户拥有的角色权限进行对比,以此来判断用户是否对某个资源具有访问权限。

1、权限管理过滤器

继承与AbstractSecurityInterceptor,实时监控用户的行为,防止用户访问未被授权的资源。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

package com.example.demo.utils.security;

 

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.access.SecurityMetadataSource;

import org.springframework.security.access.intercept.AbstractSecurityInterceptor;

import org.springframework.security.access.intercept.InterceptorStatusToken;

import org.springframework.security.web.FilterInvocation;

import org.springframework.stereotype.Service;

 

import java.io.IOException;

 

@Service

public class CustomFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {

    Logger log = LoggerFactory.getLogger(CustomFilterSecurityInterceptor.class);

    @Autowired

    private CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;  // 权限配置资源管理器

 

    

    @Autowired

    public void setMyAccessDecisionManager(CustomAccessDecisionManager customAccessDecisionManager) {

        super.setAccessDecisionManager(customAccessDecisionManager);

    }

  

    @Override

    public void init(FilterConfig filterConfig) throws ServletException {

 

    }

 

    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

 

        FilterInvocation fi = new FilterInvocation(request, response, chain);

        log.info("【权限管理过滤器】请求URL:" + fi.getRequestUrl());

        invoke(fi);

    }

  

    public void invoke(FilterInvocation fi) throws IOException, ServletException {

        //fi里面有一个被拦截的url

        //里面调用CustomFilterInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限

        //再调用CustomAccessDecisionManager的decide方法来校验用户的权限是否足够

        InterceptorStatusToken token = super.beforeInvocation(fi);

        try {

            //执行下一个拦截器

            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());

        catch(Exception e) {

            log.error("【权限管理过滤器】【异常】" + e.getMessage(), e);

        finally {

            super.afterInvocation(token, null);

        }

    }

 

    @Override

    public void destroy() {

 

    }

 

    @Override

    public Class<?> getSecureObjectClass() {

        return FilterInvocation.class;

    }

 

    @Override

    public SecurityMetadataSource obtainSecurityMetadataSource() {

        return this.customFilterInvocationSecurityMetadataSource;

    }

}

2、权限管理决断器

权限管理的关键部分就是决断器,它实现了AccessDecisionManager,重写了decide方法,使用自定义的决断器,在用户访问受保护的资源时,决断器判断用户拥有的角色中是否对改资源具有访问权限,如果没有,则拒绝访问

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

package com.example.demo.utils.security;

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.security.access.AccessDecisionManager;

import org.springframework.security.access.AccessDeniedException;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.authentication.InsufficientAuthenticationException;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.stereotype.Service;

 

import java.util.Collection;

import java.util.Iterator;

 

@Service

public class CustomAccessDecisionManager implements AccessDecisionManager {

    Logger log = LoggerFactory.getLogger(CustomAccessDecisionManager.class);

     

    // decide 方法是判定是否拥有权限的决策方法,

    //authentication 是释CustomUserService中循环添加到 GrantedAuthority 对象中的权限信息集合.

    //object 包含客户端发起的请求的requset信息,可转换为 HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();

    //configAttributes 为MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法返回的结果,此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。如果不在权限表中则放行。

    @Override

    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

 

        if(null== configAttributes || configAttributes.size() <=0) {

            return;

        }

        ConfigAttribute c;

        String needRole;

        for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {

            c = iter.next();

            needRole = c.getAttribute();

            for(GrantedAuthority ga : authentication.getAuthorities()) {//authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合

                if(needRole.trim().equals(ga.getAuthority())) {

                    return;

                }

            }

            log.info("【权限管理决断器】需要role:" + needRole);

        }

        throw new AccessDeniedException("Access is denied");

    }

 

    @Override

    public boolean supports(ConfigAttribute attribute) {

        return true;

    }

 

    @Override

    public boolean supports(Class<?> clazz) {

        return true;

    }

}

3、权限配置资源管理器

权限配置资源管理器实现了FilterInvocationSecurityMetadataSource,在启动时就去加载了所有的权限列表,权限配置资源管理器为决断器实时提供支持,判断用户访问的资源是否在受保护的范围之内。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

package com.example.demo.utils.security;

 

import com.example.demo.dao.SysPermissionDao;

import com.example.demo.pojo.SysPermission;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.access.SecurityConfig;

import org.springframework.security.web.FilterInvocation;

import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import org.springframework.stereotype.Service;

 

import javax.servlet.http.HttpServletRequest;

import java.util.*;

 

@Service

public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired

    private SysPermissionDao sysPermissionDao;

 

    private HashMap<String, Collection<ConfigAttribute>> map =null;

 

    

    public void loadResourceDefine(){

        map = new HashMap<>();

        Collection<ConfigAttribute> array;

        ConfigAttribute cfg;

        List<SysPermission> permissions = sysPermissionDao.findAll();

        for(SysPermission permission : permissions) {

            array = new ArrayList<>();

            cfg = new SecurityConfig(permission.getName());

            //此处只添加了用户的名字,其实还可以添加更多权限的信息,例如请求方法到ConfigAttribute的集合中去。此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。

            array.add(cfg);

            //用权限的getUrl() 作为map的key,用ConfigAttribute的集合作为 value,

            map.put(permission.getUrl(), array);

        }

    }

 

    //此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。如果不在权限表中则放行。

    @Override

    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        if(map ==null) loadResourceDefine();

        //object 中包含用户请求的request 信息

        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();

        AntPathRequestMatcher matcher;

        String resUrl;

        for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {

            resUrl = iter.next();

            matcher = new AntPathRequestMatcher(resUrl);

            if(matcher.matches(request)) {

                return map.get(resUrl);

            }

        }

        return null;

    }

 

    @Override

    public Collection<ConfigAttribute> getAllConfigAttributes() {

        return null;

    }

 

    @Override

    public boolean supports(Class<?> clazz) {

        return true;

    }

}

六、根据权限设置连接

对于权限管理,我们可能希望,在一个用户访问的界面中,不是等到用户点击了超链接之后,才来判断用户有没有这个权限,而是按照用户拥有的权限来显示超链接。这样的设计对于用户体验来说,会更友好。

1、方法1:使用sec标签(thymeleaf)

在html标签中引入的Spring Security的标签:

1

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

sec:authentication="name":取当前登录用户的用户名

1

<title sec:authentication="name"></title>

sec:authorize="hasRole('ROLE_ADMIN'):表示当前用户是否拥有角色ROLE_ADMIN

1

<li sec:authorize="hasRole('ROLE_ADMIN')"><a th:href="@{/admin}"> admin </a></li>

sec:authorize="hasAuthority('admin')":表示当前用户是否拥有权限admin

1

<li sec:authorize="hasAuthority('admin')"><a th:href="@{/admin}"> admin </a></li>

2、方法二:代码

在控制层用代码获取是否有权限,然后将标识放入内容中,页面获取处理

七、其它代码

1、controller

IndexController.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

package com.example.demo.controller;

 

import com.example.demo.domain.Msg;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

 

@Controller

public class IndexController {

    

    @RequestMapping("/")

    public String index(Model model){

        Msg msg =  new Msg("测试标题","测试内容","欢迎来到HOME页面,您拥有index权限");

        model.addAttribute("msg", msg);

        return "home";

    }

 

    

    @RequestMapping("/index2")

    public String index2(Model model){

        Msg msg =  new Msg("测试标题2","测试内容2","欢迎来到HOME页面,您拥有home权限");

        model.addAttribute("msg", msg);

        return "home";

    }

 

    @RequestMapping("/admin")

    @ResponseBody

    public String hello(){

        return "hello admin";

    }

 

    @RequestMapping("/yk")

    @ResponseBody

    public String hello2(){

        return "hello yk";

    }

}

2、dao

SysUserDao.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.example.demo.dao;

 

import com.example.demo.pojo.SysUser;

import org.apache.ibatis.annotations.Mapper;

 

@Mapper

public interface SysUserDao {

    public SysUser findByUserName(String username);

}

SysPermissionDao.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package com.example.demo.dao;

 

import com.example.demo.pojo.SysPermission;

import org.apache.ibatis.annotations.Mapper;

 

import java.util.List;

 

@Mapper

public interface SysPermissionDao {

    List<SysPermission> findAll();

    List<SysPermission> findByAdminUserId(Long userId);

}

3、domain

Msg.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

package com.example.demo.domain;

 

public class Msg {

    private String title;

    private String content;

    private String etraInfo;

    public Msg(String title, String content, String etraInfo) {

        super();

        this.title = title;

        this.content = content;

        this.etraInfo = etraInfo;

    }

    public String getTitle() {

        return title;

    }

    public void setTitle(String title) {

        this.title = title;

    }

    public String getContent() {

        return content;

    }

    public void setContent(String content) {

        this.content = content;

    }

    public String getEtraInfo() {

        return etraInfo;

    }

    public void setEtraInfo(String etraInfo) {

        this.etraInfo = etraInfo;

    }

}

4、pojo

SysUser.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

package com.example.demo.pojo;

 

import java.util.List;

 

public class SysUser {

    private Long id;

    private String username;

    private String passWord;

 

    private List<SysRole> roles;

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getUsername() {

        return username;

    }

 

    public void setUsername(String username) {

        this.username = username;

    }

 

    public String getPassword() {

        return password;

    }

 

    public void setPassword(String password) {

        this.password = password;

    }

 

    public List<SysRole> getRoles() {

        return roles;

    }

 

    public void setRoles(List<SysRole> roles) {

        this.roles = roles;

    }

}

SysRole.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

package com.example.demo.pojo;

 

public class SysRole {

    private Long id;

    private String name;

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

}

SysPermission.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

package com.example.demo.pojo;

 

public class SysPermission {

    private Long id;

    //权限名称

    private String name;

 

    //权限描述

    private String descritpion;

 

    //授权链接

    private String url;

 

    //父节点id

    private int pid;

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public String getDescritpion() {

        return descritpion;

    }

 

    public void setDescritpion(String descritpion) {

        this.descritpion = descritpion;

    }

 

    public String getUrl() {

        return url;

    }

 

    public void setUrl(String url) {

        this.url = url;

    }

 

    public int getPid() {

        return pid;

    }

 

    public void setPid(int pid) {

        this.pid = pid;

    }

}

5、mapperXX.xml

SysUserDao.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.example.demo.dao.SysUserDao" >

    <resultMap id="userMap" type="SysUser">

        <id property="id" column="ID"/>

        <result property="username" column="username"/>

        <result property="password" column="PASSWORD"/>

        <collection property="roles" ofType="SysRole">

            <result column="name" property="name"/>

        </collection>

    </resultMap>

    <select id="findByUserName" parameterType="String" resultMap="userMap">

        select u.*

        ,r.name

        from sys_user u

        LEFT JOIN sys_user_role sru on u.id= sru.sys_user_id

        LEFT JOIN sys_role r on sru.sys_role_id=r.id

        where username= #{username}

    </select>

</mapper>

SysPermissionDao.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.example.demo.dao.SysPermissionDao" >

    <select id="findAll"  resultType="SysPermission">

        SELECT * from sys_permission ;

    </select>

 

    <select id="findByAdminUserId" parameterType="java.lang.Long" resultType="SysPermission">

 

      SELECT

        p.*

      FROM sys_user u

      LEFT JOIN sys_user_role sru ON u.id= sru.sys_user_id

      LEFT JOIN sys_role r ON sru.sys_role_id=r.id

      LEFT JOIN sys_role_permission spr ON spr.sys_role_id=r.id

      LEFT JOIN Sys_permission p ON p.id =spr.sys_permission_id

      WHERE u.id=#{userId}

 </select>

</mapper>

6、html

login.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>

    <meta content="text/html;charset=UTF-8"/>

    <title>登录页面</title>

    <link rel="stylesheet" th:href="@{CSS/bootstrap.min.css}"/>

    <style type="text/css">

        body {

            padding-top: 50px;

        }

        .starter-template {

            padding: 40px 15px;

            text-align: center;

        }

    </style>

</head>

<body>

 

<nav class="navbar navbar-inverse navbar-fixed-top">

    <div class="container">

        <div class="navbar-header">

            <a class="navbar-brand" href="#">Spring Security演示</a>

        </div>

        <div id="navbar" class="collapse navbar-collapse">

            <ul class="nav navbar-nav">

                <li><a th:href="@{/}"> 首页 </a></li>

 

            </ul>

        </div><!--/.nav-collapse -->

    </div>

</nav>

<div class="container">

 

    <div class="starter-template">

        <p th:if="${param.logout}" class="bg-warning">已成功注销</p><!-- 1 -->

        <p th:if="${param.illegal}" class="bg-warning">无权访问,请切换账号登录</p><!-- 1 -->

        <p th:if="${param.error}" class="bg-danger">用户名或密码错误</p<!-- 2 -->

        <h3>使用账号密码登录</h3>

        <form name="form" th:action="@{/login}" action="/login" method="POST"<!-- 3 -->

            <div class="form-group">

                <label for="username">账号</label>

                <input type="text" class="form-control" name="username" value="" placeholder="账号" />

            </div>

            <div class="form-group">

                <label for="password">密码</label>

                <input type="password" class="form-control" name="password" placeholder="密码" />

            </div>

            <input type="submit" id="login" value="Login" class="btn btn-primary" />

        </form>

    </div>

</div>

</body>

</html>

home.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org"

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

<head>

    <meta content="text/html;charset=UTF-8"/>

    <title sec:authentication="name"></title>

    <link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />

    <style type="text/css">

        body {

            padding-top: 50px;

        }

        .starter-template {

            padding: 40px 15px;

            text-align: center;

        }

    </style>

</head>

<body>

<nav class="navbar navbar-inverse navbar-fixed-top">

    <div class="container">

        <div class="navbar-header">

            <a class="navbar-brand" href="#">Spring Security演示</a>

        </div>

        <div id="navbar" class="collapse navbar-collapse">

            <ul class="nav navbar-nav">

                <li><a th:href="@{/}"> 首页 </a></li>

                <li sec:authorize="hasAuthority('admin')"><a th:href="@{/admin}"> admin </a></li>

            </ul>

        </div><!--/.nav-collapse -->

    </div>

</nav>

  

<div class="container">

 

    <div class="starter-template">

        <h2 th:text="${msg.title}"></h2>

 

        <p class="bg-primary" th:text="${msg.content}"></p>

 

        <div>

            <p class="bg-info" th:text="${msg.etraInfo}"></p>

        </div>

        <form th:action="@{/logout}" method="post">

            <input type="submit" class="btn btn-primary" value="注销"/>

        </form>

    </div>

 

</div>

  

</body>

</html>

感谢各位的阅读,以上就是“SpringCloud的spring-security怎么配置”的内容了,经过本文的学习后,相信大家对SpringCloud的spring-security怎么配置这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: SpringCloud的spring-security怎么配置

本文链接: https://www.lsjlt.com/news/241158.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringCloud的spring-security怎么配置
    这篇文章主要讲解了“SpringCloud的spring-security怎么配置”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringCloud的spring-security怎么配置...
    99+
    2023-06-05
  • 详解Spring Security 简单配置
    开发环境 maven idea jdk 1.8 tomcat 8配置spring mvc + spring securitypom.xml <properties> <spring.version>4.3....
    99+
    2023-05-31
    spring security 配置
  • Spring Security核心配置有哪些
    这篇文章主要讲解了“Spring Security核心配置有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Spring Security核心配置有哪些”吧!核心配置解读3.1 功能介绍这...
    99+
    2023-06-04
  • 详解spring security 配置多个AuthenticationProvider
    前言发现很少关于spring security的文章,基本都是入门级的,配个UserServiceDetails或者配个路由控制就完事了,而且很多还是xml配置,国内通病...so,本文里的配置都是java配置,不涉及xml配置,事实上我也...
    99+
    2023-05-31
    spring security 配置
  • Spring Security配置保姆级教程
    目录背景一、前言二、配置HttpSecurity三、配置WebSecurity四、配置LDAP认证五、配置JDBC认证六、In-Memory Authentication七、配置全局...
    99+
    2023-02-15
    Spring Security配置 Spring Security
  • 使用Spring Security怎么JSON进行配置并登录
    这期内容当中小编将会给大家带来有关使用Spring Security怎么JSON进行配置并登录,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。准备工作基本的spring security配置就不说了,网上一...
    99+
    2023-05-31
    spring security json
  • 【Spring Security】WebSecurityConfigurerAdapter被deprecated怎么办?官方推荐新的Security配置风格总结
    h 本期目录 背景一、 前言二、 配置HttpSecurity三、 配置WebSecurity四、 配置LDAP认证五、 配置JDBC认证六、 In-Memor...
    99+
    2024-01-21
    spring java mybatis web安全 系统安全
  • Spring Security 6 配置方法,废弃 WebSecurityConfigurerAdapter
    一、背景   最近阿里云的项目迁回本地运行,数据库从阿里云的RDS(即Mysql5.6)换成了本地8.0,Redis也从古董级别的2.x换成了现在6,忍不住,手痒,把jdk升级到了17,用zgc垃圾回收器,源代码重新编译重新发布,结果碰到...
    99+
    2023-08-31
    spring java 后端
  • Spring Security 6.0(spring boot 3.0) 下认证配置流程
    目录 前提将要实现的功能依赖(POM)示例代码基础组件验证码MyUserDetailsServiceImpl(认证/权限信息)MyAuthenticationHandler(Handler)MyRememberMeServices(...
    99+
    2023-08-23
    spring boot spring java
  • Spring security权限配置与使用大全
    简介 Spring Security 是为了基于Spring的应用程序提供的声明式安全保护的安全性框架。Spring Security 提供了完整的安全性解决方案,它能够在Web请...
    99+
    2024-04-02
  • spring security国际化及UserCache的配置和使用
    国际化配置<!-- 定义上下文返回的消息的国际化 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableRe...
    99+
    2023-05-31
    spring security 国际化
  • SpringCloud之SpringCloud gateway网关路由怎么配置
    本篇内容介绍了“SpringCloud之SpringCloud gateway网关路由怎么配置”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够...
    99+
    2023-07-05
  • SpringCloud GateWay网关怎么配置
    本文小编为大家详细介绍“SpringCloud GateWay网关怎么配置”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringCloud GateWay网关怎么配置”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢...
    99+
    2023-06-30
  • Spring Security怎么使用
    这篇文章主要介绍“Spring Security怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring Security怎么使用”文章能帮助大家解决问题。Spring...
    99+
    2023-06-30
  • Spring Security登录表单配置示例详解
    目录Spring Security登录表单配置1.引入pom依赖2.bootstrap.yml添加配置3.创建login.html4.创建配置类5.配置细节6.登陆成功7.登陆失败8...
    99+
    2024-04-02
  • Spring Security的相关配置方法及功能实现
    本篇内容介绍了“Spring Security的相关配置方法及功能实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够...
    99+
    2024-04-02
  • springcloud负载均衡怎么配置
    Spring Cloud提供了多种负载均衡的方式,可以通过在配置文件中配置相关参数来进行配置。 使用Ribbon负载均衡器: 在...
    99+
    2023-10-26
    springcloud
  • Swagger2怎么配置Security授权认证
    本篇内容主要讲解“Swagger2怎么配置Security授权认证”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Swagger2怎么配置Security授权认证”吧!Swagger2配置Secu...
    99+
    2023-07-05
  • SpringCloud Gateway动态路由怎么配置
    这篇“SpringCloud Gateway动态路由怎么配置”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Spri...
    99+
    2023-07-05
  • 如何解决Spring Security的权限配置不生效问题
    这篇文章主要介绍如何解决Spring Security的权限配置不生效问题,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Spring Security权限配置不生效在集成Spring Security做接口...
    99+
    2023-06-29
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作