SpringSecurity的入门应用

官网:spring security reference

通过内存进行认证授权

Authorize Requests 授权/认证

在这里插入图片描述
可以通过向方法添加多个子项来为 URL 指定自定义要求http.authorizeRequests()。
例如:

package com.example.project.config;

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.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

protected void configure(HttpSecurity http) throws Exception {
	http.authorizeRequests()                                                                
		.antMatchers("/resources/**", "/signup", "/about").permitAll()                  
		.antMatchers("/admin/**").hasRole("ADMIN")                                      
		.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            
		.anyRequest().authenticated()                                                   
		.and()
		// ...
		.formLogin();
}

http.authorizeRequests()方法有多个子项,每个匹配器都按照声明的顺序进行考虑。

指定了任何用户都可以访问的多个 URL 模式。
具体来说,如果 URL 以“/resources/”开头、等于“/signup”或等于“/about”,则任何用户都可以访问请求。

任何以“/admin/”开头的 URL 都将被限制为具有角色“ROLE_ADMIN”的用户。
您会注意到,由于我们正在调用该hasRole方法,因此我们不需要指定“ROLE_”前缀。

任何以“/db/”开头的 URL 都要求用户同时拥有“ROLE_ADMIN”和“ROLE_DBA”。
您会注意到,由于我们使用的是hasRole表达式,因此不需要指定“ROLE_”前缀。

任何尚未匹配的 URL 只需要对用户进行身份验证
xxx.and().formLogin();

.and()相当于一个通用前缀的效果,因为.formLogin()实际上是http.formLogin(),当我们使用链式编程可以直接将他们连接起来。
formLogin()可以在没有权限自动跳转到默认登录界面。

密码加密认证

package com.example.project.config;

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.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程通过静态内部类方式实现零件无序装配,这种方式使用更加灵活,更符合定义。
    // 内部有复杂对象的默认实现,使用时可以根据用户需求自由定义更改内容,并且无需改变具体的构造方式。就可以生产出不同复杂产品
    @Override
    protected void configure(HttpSecurity http) throws Exception {//授权
        //通过路径设置授权限制访问
        http.authorizeHttpRequests()
                .antMatchers("/").permitAll()//对于默认/来说允许所有人访问
                .antMatchers("/index").hasRole("users")//只允许用户可以登录index页面

                .and()
                .formLogin();//没有权限会自动跳转到默认登录界面
    }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //密码编码PasswordEncoder mapped for the id "null"要求对密码加密

        //正常来讲会从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//设置密码加密方式
                .withUser("Dave").password(new BCryptPasswordEncoder().encode("123456")).roles("users")//设置密码编码方式,roles中可以设置多个权限比如.roles("users","admin")
                .and()
                .withUser("David").password(new BCryptPasswordEncoder().encode("123456")).roles("users")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("users");
    }
}

通过数据库认证授权

JDBC Authentication

找到支持基于 JDBC 的身份验证的更新。下面的示例假定您已经DataSource在应用程序中定义了 a。以下示例提供了使用基于 JDBC 的身份验证的完整示例。

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	auth
		.jdbcAuthentication()
			.dataSource(dataSource)
			.withDefaultSchema()
			.withUser("user").password("password").roles("USER").and()
			.withUser("admin").password("password").roles("USER", "ADMIN");
}

前端判断登录和权限

 <!--判断是否有权限-->
                        <div class="app-utility-item">
                            <div sec:authorize="!hasRole('users')">
                                失败:<span sec:authentication="name"></span><!--名字-->
                                <!--                                角色:<span sec:authentication="principal.getAuthorities()"></span>&lt;!&ndash;权限&ndash;&gt;-->
                            </div>
                        </div>

                        <!--登录成功-->
                        <div class="app-utility-item">
                            <div sec:authorize="isAuthenticated()">
                                用户名:<span sec:authentication="name"></span><!--名字-->
<!--                                角色:<span sec:authentication="principal.getAuthorities()"></span>&lt;!&ndash;权限&ndash;&gt;-->
                            </div>
                        </div>


                        <div class="app-utility-item">
                            <div sec:authorize="isAuthenticated()">
                                <a th:href="@{/logout}" th:title="注销">
                                    <i class="sign-out icon"></i>注销
                                </a>
                            </div>
                        </div>

整个文件

package com.example.project.config;

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.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程通过静态内部类方式实现零件无序装配,这种方式使用更加灵活,更符合定义。
    // 内部有复杂对象的默认实现,使用时可以根据用户需求自由定义更改内容,并且无需改变具体的构造方式。就可以生产出不同复杂产品
    @Override
    protected void configure(HttpSecurity http) throws Exception {//授权
        //通过路径设置授权限制访问
        http.authorizeHttpRequests()
                //设置访问权限
                .antMatchers("/").permitAll()//对于默认/来说允许所有人访问
                .antMatchers("/index").hasRole("users")//只允许用户可以登录index页面
                .and()
                //没有权限会自动跳转到默认登录界面
                .formLogin()
//                .loginPage("/login")//用户未登录时,访问任何资源都转跳到该路径,即登录页面
//                .loginProcessingUrl("/login")//登录表单form中action的地址,也就是处理认证请求的路径
//                .usernameParameter("name")///登录表单form中用户名输入框input的name名,不修改的话默认是username
//                .passwordParameter("password")//form中密码输入框input的name名,不修改的话默认是password
                .defaultSuccessUrl("/index")//登录认证成功后默认转跳的路径,这一行如果不加,会继续跳转到自己的login页面
                .and()
                //开启注销功能,注销成功返回注册页面
                .logout().logoutSuccessUrl("/")
                .and()
                ;

        //防止网站攻击 get不太安全 post较安全
        http.csrf().disable();//关闭csrfCSRF(Cross-site request forgery)
        // 也被称为:one click attack/session riding,中文名称:跨站请求伪造,缩写为:CSRF/XSRF。

        //开启记住我功能,本质就是个cookie
        http.rememberMe();
        //http.rememberMe().rememberMeParameter("");//这边可以通过获取html上设置的remember(如CheckBox)判定

    }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //密码编码PasswordEncoder mapped for the id "null"要求对密码加密

        //正常来讲会从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//设置密码加密方式
                .withUser("Dave").password(new BCryptPasswordEncoder().encode("123456")).roles("users")//设置密码编码方式
                //,roles中可以设置多个权限比如.roles("users","admin")
                .and()
                .withUser("David").password(new BCryptPasswordEncoder().encode("123456")).roles("users")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("users");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值