Springboot+Spring secuirty 鍚庡彴鑿滃崟鏉冮檺璁捐

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot+Spring secuirty 鍚庡彴鑿滃崟鏉冮檺璁捐相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/art' title='art'>art   鐢ㄦ埛淇℃伅   real   鑾峰彇鐢ㄦ埛淇℃伅   html   list   tpm   grant   exception   

鑳屾櫙锛氳彍鍗曞拰鏉冮檺鍦ㄧ郴缁熶腑鏄潪甯搁噸瑕佺殑浜嬫儏锛屽湪缁撳悎鑷繁鐮旂┒杩囩殑Spring security鍜岄」鐩墠鍚庣瀹炶返涓杩涜鎬荤粨銆?/p>

浠嬬粛锛氫娇鐢ㄥ熀浜嶳BAC鏉冮檺妯″瀷锛岄拡瀵硅鑹插垎閰嶄笉鍚岀殑鏉冮檺

鎶€鏈浘鐗? src=

鏁版嵁搴撹璁★細

绯荤粺鑿滃崟                                                绯荤粺瑙掕壊                                              鑿滃崟瑙掕壊琛?/p>

 

鎶€鏈浘鐗? src=      鎶€鏈浘鐗? src=           鎶€鏈浘鐗? src=             

  鐢ㄦ埛瀵瑰簲鐨勮鑹?nbsp;                              鐢ㄦ埛淇℃伅

 鎶€鏈浘鐗? src=                鎶€鏈浘鐗? src=

鎶€鏈細Spring security+jjwt

Spring security锛氭槸Spring 寮€婧愮殑鏉冮檺绠$悊妗嗘灦锛岀敱涓€缁勮繃婊ゅ櫒閾剧粍鎴愶紝瀵逛笉鍚岀殑璁块棶杩涘幓鎷︽埅鍜屾帶鍒讹紝涔熷彲浠ヨ嚜宸卞疄鐜版潈闄愭嫤鎴?/p>

spring security 鐨勬牳蹇冨姛鑳戒富瑕佸寘鎷細

  • 璁よ瘉 锛堜綘鏄皝锛?/li>
  • 鎺堟潈 锛堜綘鑳藉共浠€涔堬級
  • 鏀诲嚮闃叉姢 锛堥槻姝吉閫犺韩浠斤級

jjwt:鏄竴涓彁渚涚鍒扮鐨凧WT鍒涘缓鍜岄獙璇佺殑Java搴擄紝鍙互鐢熸垚鍔犲瘑鐨則oken锛屽苟鍙互浠巘oken鍙嶆帹鍑哄瓨鏀惧湪token鐨勪竴浜涗俊鎭紙濡傜敤鎴疯处鍙凤級——鍙傝€冨畼缃?a href="https://jwt.io/introduction/">https://jwt.io/introduction/

 

瀹炵幇锛氶€氳繃UserDetailsService 鍜孶serDetails 閫氳繃鏁版嵁搴撹幏鍙栫敤鎴蜂俊鎭(鏉冮檺,鐢ㄦ埛璐﹀彿)

姝ラ涓€锛?/p>

// 瀹氫箟jjwt鐨勭敤鎴风殑涓€浜涗俊鎭紝鍦ㄥ悗闈㈢敓鎴恡oken鏃堕渶瑕?骞朵笖Spring security瑕佽幏鍙栧疄鐜癠serDetails 鎺ュ彛鐢ㄦ埛淇℃伅銆€銆€
@Getter @AllArgsConstructor
public class SystemUser implements UserDetails { @JSONField(serialize = false) private final Long id; private final String username; @JSONField(serialize = false) private final String password; public Long getId() { return id; } private final String salt;
// 鏉冮檺 @JSONField(serialize
= false) private final Collection<GrantedAuthority> authorities; @JSONField(serialize = false) @Override public boolean isAccountNonExpired() { return true; } @JSONField(serialize = false) @Override public boolean isAccountNonLocked() { return true; } @JSONField(serialize = false) @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return false; } @JSONField(serialize = false) @Override public String getPassword() { return password; } public Collection getRoles() { return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet()); } }

 

姝ラ浜岋細瀹炵幇 UserDetailsService 鎺ュ彛锛岃繖閲屾垜浣跨敤mybatis鏌ヨ鏁版嵁搴擄紝閫氳繃鐢ㄦ埛璐﹀彿鑾峰彇鏁版嵁搴撶敤鎴蜂俊鎭?/p>

public class SystemUserDetailsService implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private JwtPermissionService permissionService; // 鑾峰彇鐢ㄦ埛瑙掕壊鐨勮彍鍗曟潈闄?
    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUser user = userService.findByName(username);
        if (user == null) {
            throw new ServiceException("璐﹀彿涓嶅瓨鍦?);
        } else {
            if (user.getUserStatus().equals(Constants.OrganizationStatus.DISABLE)) {
                throw new ServiceException("璐﹀彿宸茶绂佺敤");
            }
            return createJwtUser(user);
        }
    }

    public UserDetails createJwtUser(SysUser user) {
        return new SystemUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getSalt(),
                permissionService.mapToGrantedAuthorities(user),
                user.getCreateTime()
        );
    }
}

銆€銆€

姝ラ涓夛細JwtPermissionService 瀹炵幇,璇锋敞鎰忚繖鏄疄鐜扮殑铏氬亣閫昏緫锛屽叿浣撶殑杩樿鐪嬩笟鍔¢€昏緫

@Component
public class JwtPermissionService{

@Autowired
private IUsersRolesService usersRolesService;
@Autowired
private IRolesMenuService rolesMenuService;

public Collection<GrantedAuthority> mapToGrantedAuthorities(SysUser user){
// step 1 鏍规嵁鐢ㄦ埛璐﹀彿鑾峰彇鐢ㄦ埛鐨勮鑹?br /> Set<Role> menu =usersRolesService.getRole(String userName);
// step 2 鏍规嵁瑙掕壊鑾峰彇鐢ㄦ埛鐨勮彍鍗?br />
Set<Menu>menuList=rolesMenuService.getMenu(Set<Role>role);
 // step 3 鑾峰彇鑿滃崟瀵瑰簲鐨刴enu_make 杩涜杞崲

return menuVos.stream().filter(x -> !StringUtils.isEmpty(x.getMenuMark())).map(
        result -> {
String permission =result.getMenuMark();

return new SimpleGrantedAuthority(permission);
 }
).collect(Collectors.toList());
}
}

 

 姝ラ4锛氬畾涔塖pring security  鏉冮檺閰嶇疆

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtTokenFilter tokenFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(jwtUserDetailsService)
.passwordEncoder(passwordEncoderBean());
}
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
// 鍘绘帀鍓嶇紑
return new GrantedAuthorityDefaults("");
}

// 鍔犲瘑鏂瑰紡
@Bean
public PasswordEncoder passwordEncoderBean() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}// 鏉冮檺鎷︽埅瑙勫垯锛屽崈涓囦笉瑕?login() 杩欑洿鎺ヨ蛋琛ㄥ崟楠岃瘉浜嗭紝浼氭瘮杈冮夯鐑?
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

httpSecurity

// 绂佺敤 CSRF
.csrf().disable()
// 涓嶅垱寤轰細璇?br /> .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 杩囨护璇锋眰
.authorizeRequests()
.antMatchers(
HttpMethod.GET,
"/*.html",
"/**/*.html",
"/**/*.css",
"/**/*.js"
).anonymous()

.antMatchers( HttpMethod.POST,"/auth/login).permitAll()
.antMatchers("/websocket/**").anonymous()
// 鎵€鏈夎姹傞兘闇€瑕佽璇?br /> .anyRequest().authenticated()
// 闃叉iframe 閫犳垚璺ㄥ煙
.and().headers().frameOptions().disable();
// 娣诲姞鑷畾涔夋嫤鎴櫒
httpSecurity
.addFilterBefore(
tokenFilter,UsernamePasswordAuthenticationFilter.class);
    }}

 

 姝ラ4锛氳嚜瀹氫箟鎷︽埅鍣紝閫氳繃姝ゆ嫤鎴櫒锛?鍓嶇璁块棶鏃跺€欏ご閮ㄨ甯?Authorization"锛岄€氳繃token鑾峰彇鐢ㄦ埛淇℃伅

@Component
public class JwtTokenFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
 
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String requestHeader = request.getHeader("Authorization");
String authToken=null;
if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
authToken = requestHeader.substring(7);
String userName =Jwts.parser().setSigningKey(secret).parseClaimsJws(authToken ).getBody().getSubject();

}

if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
SystemUser userDetails = (SystemUser ) this.userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
}
}

 

姝ラ浜旓細鐧诲綍杩斿洖toekn 缁欏墠绔?/p>

@Getter
@AllArgsConstructor
public class AuthenticationInfo implements Serializable {

private final String token;

private final JwtUser user;
}

// 鐧诲綍鏋勯€犲櫒

@RequestMapping("auth") public class SecurityController{
@Autowired
@Qualifier("SystemUserDetailsService")
private UserDetailsService userDetailsService;
@PostMapping(value = "${jwt.auth.path}")
public AuthorizationUser login(@RequestParam("userName")String userName,@RequestParam("password")String password)) {
    final SystemUser jwtUser = (SystemUser ) userDetailsService.loadUserByUsername(userName);
    //鑾峰彇鐢ㄦ埛鐨則oken,鏄惁瀛樺湪
Date expirationDate = new Date(createdDate.getTime() +864000);
    String token =Jwts.builder()
.setClaims(claims)
.setSubject()
.setIssuedAt(new Date)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();

return new AuthenticationInfo(token, jwtUser));
}

}

 

姝ラ6 瀹氫箟鍏锋湁鏌愪釜鑿滃崟鐨勬瀯閫犲櫒,鍓嶇閫氳繃瀹氫箟鑿滃崟鏍囪瘑璺熷悗鍙癅PreAuthorize 瀵瑰簲鐨勬潈闄愯繘琛屽叧鑱旇捣鏉ワ紝杩欐牱灏卞彲浠ュ舰鎴愬搴旂殑鏉冮檺

@RequestMapping("/admin")
public class Demo {

@RequestMapping("/pageList")
@PreAuthorize("hasAnyRole(‘menu_mark’)")
public List<String> pageList(){
return new ArrayList();
}
}

 

SystemUser 

以上是关于Springboot+Spring secuirty 鍚庡彴鑿滃崟鏉冮檺璁捐的主要内容,如果未能解决你的问题,请参考以下文章

spring 和springboot的区别

SpringBoot:简述SpringBoot和Spring的区别

Spring Boot入门教程大纲

Spring boot与Spring

SpringBoot入门到精通-Spring的注解编程

从Spring到SpringBoot