最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringSecurity在單機(jī)環(huán)境下使用方法詳解

 更新時(shí)間:2025年02月15日 12:20:15   作者:java小羅_江西南昌  
本文詳細(xì)介紹了SpringSecurity和SpringBoot的整合過程,包括配置用戶認(rèn)證、JSP頁面的使用、數(shù)據(jù)庫認(rèn)證以及授權(quán)功能的實(shí)現(xiàn),感興趣的朋友一起看看吧

參考

來源于黑馬程序員: 手把手教你精通新版SpringSecurity

技術(shù)選型

SpringBoot2.1.3,SpringSecurity,MySQL,mybatis,jsp

初步整合認(rèn)證第一版

創(chuàng)建工程并導(dǎo)入jar包

先只導(dǎo)入SpringBoot

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

提供處理器

@Controller
@RequestMapping("/product")
public class ProductController {
    @RequestMapping
    @ResponseBody
	public String hello(){
    	return "success";
    }
}

編寫啟動(dòng)類

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

測(cè)試效果

使用SpringBoot內(nèi)置tomcat啟動(dòng)項(xiàng)目,即可訪問處理器。

加入SpringSecurity的jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

重啟再次測(cè)試

SpringBoot已經(jīng)為SpringSecurity提供了默認(rèn)配置,默認(rèn)所有資源都必須認(rèn)證通過才能訪問。

那么問題來了!此刻并沒有連接數(shù)據(jù)庫,也并未在內(nèi)存中指定認(rèn)證用戶,如何認(rèn)證呢?

其實(shí)SpringBoot已經(jīng)提供了默認(rèn)用戶名user,密碼在項(xiàng)目啟動(dòng)時(shí)隨機(jī)生成,如圖:

認(rèn)證通過后可以繼續(xù)訪問處理器資源:

整合認(rèn)證第二版

加入jsp,使用自定義認(rèn)證頁面

說明

SpringBoot官方是不推薦在SpringBoot中使用jsp的,那么到底可以使用嗎?答案是肯定的!

不過需要導(dǎo)入tomcat插件啟動(dòng)項(xiàng)目,不能再用SpringBoot默認(rèn)tomcat了。

我們不能 通過啟動(dòng)類的方式來進(jìn)行啟動(dòng)了,因?yàn)樗鼤?huì)不識(shí)別Jsp頁面,必須導(dǎo)入jar包,然后更換方法

導(dǎo)入SpringBoot的tomcat啟動(dòng)插件jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

加入jsp頁面等靜態(tài)資源

在src/main目錄下創(chuàng)建webapp目錄

這時(shí)webapp目錄并不能正常使用,因?yàn)橹挥衱eb工程才有webapp目錄,在pom文件中修改項(xiàng)目為web工程

這時(shí)webapp目錄,可以正常使用了!

導(dǎo)入第一天案例中靜態(tài)資源,注意WEB-INF就不用了哈!

修改login.jsp中認(rèn)證的url地址

修改header.jsp中退出登錄的url地址

提供SpringSecurity配置類

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //指定認(rèn)證對(duì)象的來源
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    //SpringSecurity配置信息
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll()
                .antMatchers("/product").hasAnyRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.jsp")
                .loginProcessingUrl("/login")
                .successForwardUrl("/index.jsp")
                .failureForwardUrl("/failer.jsp")
                .and()
                .logout()
                .logoutSuccessUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/login.jsp")
                .and()
                .csrf()
                .disable();
    }
}

修改產(chǎn)品處理器

有頁面了,就跳轉(zhuǎn)一個(gè)真的吧!

@Controller
@RequestMapping("/product")
public class ProductController {
    @RequestMapping("/findAll")
    public String findAll(){
	    return "product-list";
    }
}

配置視圖解析器

使用tomcat插件啟動(dòng)項(xiàng)目

測(cè)試效果

自定義的認(rèn)證頁面

認(rèn)證成功頁面

整合認(rèn)證第三版【數(shù)據(jù)庫認(rèn)證】 數(shù)據(jù)庫環(huán)境準(zhǔn)備

依然使用security_authority數(shù)據(jù)庫,sql語句在第一天資料里。

導(dǎo)入數(shù)據(jù)庫操作相關(guān)jar包

<!--MySQL驅(qū)動(dòng)包-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<!--springboot啟動(dòng)類-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>
<!--導(dǎo)入通用Mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

在配置文件中添加數(shù)據(jù)庫操作相關(guān)配置

在啟動(dòng)類上添加掃描dao接口包注解

image-20200920194847462

創(chuàng)建用戶pojo對(duì)象

這里直接實(shí)現(xiàn)SpringSecurity的用戶對(duì)象接口,并添加角色集合私有屬性。注意接口屬性都要標(biāo)記不參與json的處理

@Data
public class SysRole implements GrantedAuthority {
    private Integer id;
    private String roleName;
    private String roleDesc;
}

創(chuàng)建角色pojo對(duì)象

這里直接使用SpringSecurity的角色規(guī)范,我們實(shí)現(xiàn)UserDetails的類型

@Data
public class SysUser implements UserDetails {
    private Integer id;
    private String username;
    private String password;
    private Integer status;
    private List<SysRole> roles;
    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }
    @Override
    public String getPassword() {
        return password;
    }
    @Override
    public String getUsername() {
        return username;
    }
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}

提供角色mapper接口

public interface RoleMapper extends Mapper<SysRole> {
    @Select("SELECT r.id, r.role_name roleName, r.role_desc roleDesc " +
    "FROM sys_role r, sys_user_role ur " +
    "WHERE r.id=ur.rid AND ur.uid=#{uid}")
    public List<SysRole> findByUid(Integer uid);
}

提供用戶mapper接口

這里就用到了Mybatis的一對(duì)多進(jìn)行操作

public interface UserMapper extends Mapper<SysUser> {
    @Select("select * from sys_user where username = #{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roles", column = "id", javaType = List.class,
                many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid"))
    })
    public SysUser findByName(String username);
}

提供認(rèn)證service接口

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    	return userMapper.findByUsername(s);
    }
}

在啟動(dòng)類中把加密對(duì)象放入IOC容器

@SpringBootApplication
@MapperScan("com.itheima.mapper")
public class SecurityApplication {
    public static void main(String[] args) {
    	SpringApplication.run(SecurityApplication.class, args);
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
    	return new BCryptPasswordEncoder();
    }
}

修改配置類

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //指定認(rèn)證對(duì)象的來源
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    //SpringSecurity配置信息
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll()
                .antMatchers("/product").hasAnyRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.jsp")
                .loginProcessingUrl("/login")
                .successForwardUrl("/index.jsp")
                .failureForwardUrl("/failer.jsp")
                .and()
                .logout()
                .logoutSuccessUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/login.jsp")
                .and()
                .csrf()
                .disable();
    }
}

大功告成盡管測(cè)試,注意還是用插件啟動(dòng)項(xiàng)目,使用數(shù)據(jù)庫表中的用戶名和密碼。

整合實(shí)現(xiàn)授權(quán)功能

在啟動(dòng)類上添加開啟方法級(jí)的授權(quán)注解

在產(chǎn)品處理器類上添加注解

要求產(chǎn)品列表功能必須具有ROLE_ADMIN角色才能訪問!

重啟項(xiàng)目測(cè)試

再次訪問產(chǎn)品列表發(fā)現(xiàn)權(quán)限不足

指定自定義異常頁面

編寫異常處理器攔截403異常

@ControllerAdvice
public class HandleControllerException {
    @ExceptionHandler(RuntimeException.class)
    public String exceptionHandler(RuntimeException e){
    	if(e instanceof AccessDeniedException){
            //如果是權(quán)限不足異常,則跳轉(zhuǎn)到權(quán)限不足頁面!
            return "redirect:/403.jsp";
    	}
        //其余的異常都到500頁面!
        return "redirect:/500.jsp";
    }
}

再次測(cè)試產(chǎn)品列表就可以到自定義異常頁面了

到此這篇關(guān)于SpringSecurity在單機(jī)環(huán)境下使用的文章就介紹到這了,更多相關(guān)SpringSecurity單機(jī)環(huán)境使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 探究Java常量本質(zhì)及三種常量池(小結(jié))

    探究Java常量本質(zhì)及三種常量池(小結(jié))

    這篇文章主要介紹了探究Java常量本質(zhì)及三種常量池(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • Spring MVC+FastJson+Swagger集成的完整實(shí)例教程

    Spring MVC+FastJson+Swagger集成的完整實(shí)例教程

    這篇文章主要給大家分享介紹了關(guān)于Spring MVC+FastJson+Swagger集成的完整實(shí)例教程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2018-04-04
  • Java中String、StringBuffer和StringBuilder的區(qū)別與使用場(chǎng)景

    Java中String、StringBuffer和StringBuilder的區(qū)別與使用場(chǎng)景

    在Java編程中,String、StringBuffer和StringBuilder是用于處理字符串的常見類,它們?cè)诳勺冃?、線程安全性和性能方面有所不同,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-05-05
  • idea使用easyCode生成代碼(根據(jù)mybatis-plus模板創(chuàng)建自己的模板)

    idea使用easyCode生成代碼(根據(jù)mybatis-plus模板創(chuàng)建自己的模板)

    本文主要介紹了idea使用easyCode生成代碼,easyCode代碼生成器可以減少低價(jià)值搬磚,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-10-10
  • Java中的緩沖流詳細(xì)解析

    Java中的緩沖流詳細(xì)解析

    這篇文章主要介紹了Java中的緩沖流詳細(xì)解析,緩沖流可以分為字節(jié)緩沖流,字符緩沖流,字節(jié)緩沖流可分為字節(jié)輸?入緩沖流,字節(jié)輸出緩沖流,字符緩沖流可以分為字符輸入緩沖流,字符輸出緩沖流,需要的朋友可以參考下
    2023-11-11
  • 深入理解spring boot 監(jiān)控

    深入理解spring boot 監(jiān)控

    今天通過本文給大家介紹關(guān)于spring boot 監(jiān)控的相關(guān)知識(shí),引入jar包的實(shí)例代碼文中也給大家詳細(xì)介紹,對(duì)spring boot 監(jiān)控相關(guān)知識(shí)感興趣的朋友一起看看吧
    2021-10-10
  • 分頁技術(shù)原理與實(shí)現(xiàn)之Java+Oracle代碼實(shí)現(xiàn)分頁(二)

    分頁技術(shù)原理與實(shí)現(xiàn)之Java+Oracle代碼實(shí)現(xiàn)分頁(二)

    這篇文章主要介紹了分頁技術(shù)原理與實(shí)現(xiàn)的第二篇:Java+Oracle代碼實(shí)現(xiàn)分頁,感興趣的小伙伴們可以參考一下
    2016-06-06
  • Java的對(duì)象頭原理與源碼超詳細(xì)講解

    Java的對(duì)象頭原理與源碼超詳細(xì)講解

    Java對(duì)象頭是對(duì)象內(nèi)存布局的核心部分,存儲(chǔ)元數(shù)據(jù)和運(yùn)行時(shí)狀態(tài),這篇文章主要介紹了Java的對(duì)象頭原理與源碼超詳細(xì)講解的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-08-08
  • MyBatis使用自定義TypeHandler轉(zhuǎn)換類型的實(shí)現(xiàn)方法

    MyBatis使用自定義TypeHandler轉(zhuǎn)換類型的實(shí)現(xiàn)方法

    這篇文章主要介紹了MyBatis使用自定義TypeHandler轉(zhuǎn)換類型的實(shí)現(xiàn)方法,本文介紹使用TypeHandler 實(shí)現(xiàn)日期類型的轉(zhuǎn)換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-10-10
  • java實(shí)現(xiàn)將Webp轉(zhuǎn)為jpg格式方式

    java實(shí)現(xiàn)將Webp轉(zhuǎn)為jpg格式方式

    這篇文章主要介紹了java實(shí)現(xiàn)將Webp轉(zhuǎn)為jpg格式方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07

最新評(píng)論

松原市| 迁西县| 黄浦区| 鹿泉市| 澜沧| 昌宁县| 荔浦县| 肇源县| 疏附县| 从江县| 济源市| 十堰市| 中卫市| 监利县| 临沧市| 彭泽县| 庆安县| 扬州市| 泊头市| 山东省| 诸城市| 阿尔山市| 曲阜市| 天峻县| 定南县| 象山县| 察哈| 和政县| 米泉市| 都兰县| 吴川市| 依安县| 英山县| 上思县| 白山市| 麻阳| 禹州市| 清丰县| 宁晋县| 石泉县| 石城县|