String security安全框架

String security安全框架

第一步:导包

<!-- 身份验证 -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>

第二部:编写配置文件

    <!--配置不拦截的 请求-->
    <http pattern="/*.html" security="none"></http>
​
    <!-- 页面的拦截规则    use-expressions:是否启动SPEL表达式 默认是true -->
    <http use-expressions="false">
        <!-- 当前用户必须有ROLE_SELLER的角色 (ROLE_是必须这样写,后面 的字母可以自定义) 才可以访问根目录及所属子目录的资源 -->
        <intercept-url pattern="/**" access="ROLE_SELLER"/>
        <!-- 开启表单登陆功能 -->
        <form-login  login-page="/shoplogin.html" default-target-url="/admin/index.html" authentication-failure-url="/shoplogin.html" always-use-default-target="true"/>
        <csrf disabled="true"/>
        <!--使页面可以显示在集成的 网页上-->
        <headers>
            <frame-options policy="SAMEORIGIN"/>
        </headers>
        <logout/>
    </http>
​
    <!-- 认证管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailService">
            <!--解析加密的密码-->
            <password-encoder ref="passwordEncoder"></password-encoder>
        </authentication-provider>
    </authentication-manager>    <!--经得到的 service注入-->
    <beans:bean id="userDetailService" class="com.pinyougou.service.UserDetailServiceImpl">
            <beans:property name="sellerService" ref="sellerService"></beans:property>
    </beans:bean>    <!--远程连接别的项目中的service-->
     <dubbo:application name="pinyougou-shop-web" />
     <dubbo:registry address="zookeeper://192.168.25.153:2181"/>
     <dubbo:reference id="sellerService" interface="com.pinyougou.sellergoods.service.SellerService">
    </dubbo:reference>
    <!--加载解析类-->
    <beans:bean id="passwordEncoder"                               class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    </beans:bean>

第三步:将配置文件加载,在web.xml中配置;

    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring/spring-security.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>    <!--Security的入口,过滤器代理,找到springSecurityFilterChain这个类来执行请求-->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

第四部:编写认证类

public class UserDetailServiceImpl implements UserDetailsService {
​
    private SellerService sellerService;
​
    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }
​
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(" 经过了setSellerService");
​
        //构造角色列表
       List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("ROLE_SELLER"));
        //得到角色对象
        TbSeller one = sellerService.findOne(username);
        System.out.println(one);
        
        if (one!=null){
            if (one.getStatus().equals("1")){
                return new User(one.getSellerId(),one.getPassword(),list);
            }else {
                return null;
            }
        }
        return null;
    }
}

执行流程:

客户端发送登陆请求,过滤器的处理进进入到指定的认证类,认证类从根据传过来的用户名,去数据库中找数据,如果有会返回账号和密码,框架自己比较数据库中的账号密码和输入的账号密码,如一致则登陆成功,不一致则跳到指定的失败页面


总结:

1.csrf disabled="true" 关闭csrf ,如果不加会出现错误


CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站的恶意利用。

2.security="none" 设置此资源不被拦截. 如果你没有设置登录页security="none" ,将会出现以下错误


因为登录页会被反复重定向。

3.在String Security中获得登陆名字可以使用

public class LoginController {
​
    @RequestMapping("findName")
    public Map findName(){
        //获得登陆名
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Map map = new HashMap();
        map.put("name",name);
        return map;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security是一个强大的安全框架,可以在Spring应用程序中提供全面的身份验证和授权机制。下面是使用Spring Security的步骤: 1. 引入Spring Security依赖。可以在Maven或Gradle中添加以下依赖: ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.5.0</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.5.0</version> </dependency> ``` 2. 配置Spring Security。创建一个类并添加@Configuration和@EnableWebSecurity注解。在类中重写configure(HttpSecurity http)方法来定义安全规则。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/home").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("ADMIN"); } } ``` 3. 配置用户身份验证。在上面的配置中,我们使用了内存身份验证。但是,在实际应用程序中,我们需要从数据库或LDAP中获取用户信息。可以实现UserDetailsService接口并重写loadUserByUsername方法来提供自定义身份验证。 ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user.getRoles())); } private Set<GrantedAuthority> getAuthorities(Set<Role> roles) { Set<GrantedAuthority> authorities = new HashSet<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; } } ``` 4. 集成到应用程序中。可以在Spring应用程序中使用Spring Security来保护不同的URL和资源。可以在Spring MVC控制器中使用@PreAuthorize注解来定义授权规则。 ``` @Controller public class HomeController { @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value = "/home", method = RequestMethod.GET) public String home() { return "home"; } @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/admin", method = RequestMethod.GET) public String admin() { return "admin"; } } ``` 以上就是使用Spring Security框架的基本步骤。当然,Spring Security还有更多高级功能,如OAuth2身份验证等。可以参考官方文档深入学习。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值