栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring security

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring security

spring security

public class CreateUser extends User {

    private String userId;

    private String deptId;

    public CreateUser(String deptId,String userId,String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.deptId = deptId;
        this.userId = userId;
    }
}
@lombok
public class UserInfo implements Serializable {

    private String userId;

    private String username;

    private String password;

    private String deptId;

    private Boolean delFlag;
}
@Service
public class PermissionServiceImpl implements PermissionService {


    @Override
    public List getPermission(String username) {
        ArrayList xxs = new ArrayList<>();
        return xxs;
    }



}
@Service
public class UserServiceImpl implements UserService {


    @Override
    public UserInfo getUserByName(String username) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("userid_1");
        userInfo.setUsername(username);
        userInfo.setPassword("123");
        userInfo.setDeptId("deptid_1");
        userInfo.setDelFlag(false);
        return userInfo;
    }
}
public interface PermissionService {

    List getPermission(String username);

}
public interface UserService {

    UserInfo getUserByName(String username);

}
@Service
@RequiredArgsConstructor
public class DbUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfo userInfo = userService.getUserByName(username);

        String cryptPwd = passwordEncoder.encode(userInfo.getPassword());
        userInfo.setPassword(cryptPwd);

        // 查询权限, 把权限数据封装到 authorities 的集合里面
        List authorities = AuthorityUtils
                .createAuthorityList(permissionService.getPermission(username).toArray(new String[0]));

        return new CreateUser(
                userInfo.getDeptId(),
                userInfo.getUserId(),
                username,
                userInfo.getPassword(),
                !userInfo.getDelFlag(), // 注意这里是非
                true,
                true,
                true,
                authorities
        );
    }
}
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true,prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
 
}
@Configuration
@EnableWebSecurity  //启用Web安全功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Autowired
    private DbUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            //访问"/"和"/home"路径的请求都允许
            .antMatchers("/", "/home","/staff","/staff/*")
            .permitAll()
            //而其他的请求都需要认证(登录)
            .anyRequest()
            .authenticated()

            .and()
            //修改Spring Security默认的登陆界面
            .formLogin()
            .loginPage("/login")
            .permitAll()

            .and()
            .logout()
            .permitAll();
    }

    // 构建用户信息存储的方式

    // 基于内存的方式
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception{
        builder.userDetailsService(userDetailsService);
    }

}
@Controller
public class SecurityController {
 
    @GetMapping(value = {"/home","/"})
    public String home(){
        return "home";
    }
 
    @GetMapping(value = "/hello")
    public String hello(){
        return "hello";
    }
 
    @GetMapping(value = "/login")
    public String login(){
        return "login";
    }

    @GetMapping(value = "/admin")
    @Secured("ROLE_ADMIN")
    public String admin(){
        return "admin";
    }
}
@Slf4j
@Component
public class TimeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("time filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("time filter start");
        long start = System.currentTimeMillis();
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("time filter: " + (System.currentTimeMillis() - start));
        log.info("time filter finish");
    }

    @Override
    public void destroy() {
        log.info("time filter destroy");
    }
}
@SpringBootApplication
public class SecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }

}



    
    admin.html


admin page



    
        Hello.html
    
    
        

Hello [[${#httpServletRequest.remoteUser}]]!



    
        home.html
    
    
        

Welcome!

Click here to see a greeting.



    
        login.html
    
    
        
Invalid username and password.
You have been logged out.


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.4
         
    
    com.example
    security
    0.0.1-SNAPSHOT
    security
    learn security
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
            2.4.4
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.security
            spring-security-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985684.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号