SpringSecurity 原理及使用示例

原理:编写spring-security的配置类,配置好用户,角色,登录页,跨域,密码加密等,核心是将自己定义的角色和用户传递给spring security

SpringSecurityConfig类

package com.xhb.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private  CustomUserService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {


        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()  );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        System.out.println(new BCryptPasswordEncoder().encode("1"));
        http.authorizeRequests()
                // 如果有允许匿名的url,填在下面
                  .antMatchers("/music").authenticated()
                ///admin的访问角色为admin
                .antMatchers("/admin").hasRole("admin")
                .anyRequest().authenticated()
                .and()
                // 设置登陆页
                .formLogin()
                // 定制登录页面
            //    .loginPage("/managerLogin")
                // 登录认证的URL
                .loginProcessingUrl("/login")
                // 设置登陆成功页
                .defaultSuccessUrl("/sys/index").permitAll()
                // 自定义登陆用户名和密码参数,默认为username和password
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .logout().permitAll();
        // 开启注销功能,移除所有cookie
        http.logout().deleteCookies("remove").invalidateHttpSession(true);

        // 开启记住我功能,cookie实现,默认两周
        http.rememberMe()
                // 自定义表单参数
                .rememberMeParameter("remember");

        // 关闭CSRF跨域
     //   http.csrf().disable();
        //推出后跳转页
        http.logout().logoutSuccessUrl("/");

    }

}


CustomUserService类

package com.xhb.config; 
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;


@Service

public class CustomUserService implements UserDetailsService {
/*
    @Autowired
    UserMapper userService;
    @Autowired
    UserRolesMapper userRoles;
    @Autowired
    RoleMapper roleInfo;
*/

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        // 从数据库中取出用户信息
     //   UserInfo user = userService.getUserInfoByName(username);

        // 判断用户是否存在
/*        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }*/

        // 添加权限
     //   List<UserRoles> userRolesList = userRoles.getUserRolesByUserid(user.getUserid());//用户拥有的权限列表

     //   System.out.println(userRolesList.toArray().toString());
/*        for (UserRoles ur : userRolesList) {

            RoleInfo role = roleInfo.getRoleInfoByRoleid(ur.getRoleid());
            System.out.println("ROLE_" + role.getRolename());
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRolename()));
        }*/
        authorities.add(new SimpleGrantedAuthority("ROLE_" + "admin"));
        // 返回UserDetails实现类
    //    System.out.println(user.getPassword());
        return new User("1",new BCryptPasswordEncoder().encode("1"), authorities);
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值