SpringBoot整合Spring Security 方法安全

部分引自 www.javaboy.org
在 SecurityConfig 上添加注解

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("yzn").password("$2a$10$WuUO9k/3LfTGzMEAKxNtAenttd9ulTq7wTj17ojqbU44Q5rwN/mWu").roles("admin")
                .and()
                .withUser("test").password("$2a$10$WuUO9k/3LfTGzMEAKxNtAenttd9ulTq7wTj17ojqbU44Q5rwN/mWu").roles("user");
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("admin", "user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 登錄處理接口
                .loginProcessingUrl("/doLogin")
                // 定義登錄頁面汁果,未登錄時谓传,訪問一個需要登錄之后才能訪問的接口,會自動跳轉(zhuǎn)到該頁面
                .loginPage("/login")
                //定義登錄時凡人,用戶名的 key滓玖,默認為 username
                .usernameParameter("uname")
                //定義登錄時坪哄,用戶密碼的 key,默認為 password
                .passwordParameter("passwd")
                //登錄成功的處理器
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        Map<String,Object> map = new HashMap();
                        map.put("status", 200);
                        // authentication.getPrincipal() 可以把登錄者信息取出來
                        map.put("msg", authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        Map<String,Object> map = new HashMap();
                        map.put("status", 200);
                        map.put("msg", "failed");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                    }
                })
                //和表單登錄相關(guān)的接口統(tǒng)統(tǒng)都直接通過
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        Map<String,Object> map = new HashMap();
                        map.put("status", 200);
                        map.put("msg", "注銷登錄成功");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                    }
                })
                .and()
                .csrf().disable();
    }
}

添加Service

package org.javaboy.security.service;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

@Service
public class MethodService {

    @PreAuthorize("hasRole('admin')")
    public String admin() {
        return "hello admin";
    }

    @Secured("ROLE_user")
    public String user() {
        return "hello user";
    }

    @PreAuthorize("hasAnyRole('admin','user')")
    public String hello() {
        return "hello hello";
    }
}

Controller

@RestController
public class HelloController {

    @Autowired
    MethodService methodService;

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "hello user";
    }

    @GetMapping("/login")
    public String login() {
        return "please login!!!";
    }

    @GetMapping("/hello1")
    public String hello1() {
        return methodService.admin();
    }

    @GetMapping("/hello2")
    public String hello2() {
        return methodService.user();
    }

    @GetMapping("/hello3")
    public String hello3() {
        return methodService.hello();
    }
}

測試hello1,hello2,hello3接口呢撞,發(fā)現(xiàn)方法已經(jīng)保護起來了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末损姜,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子殊霞,更是在濱河造成了極大的恐慌摧阅,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绷蹲,死亡現(xiàn)場離奇詭異棒卷,居然都是意外死亡,警方通過查閱死者的電腦和手機祝钢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門比规,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拦英,你說我怎么就攤上這事蜒什。” “怎么了疤估?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵灾常,是天一觀的道長霎冯。 經(jīng)常有香客問我,道長钞瀑,這世上最難降的妖魔是什么沈撞? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮雕什,結(jié)果婚禮上缠俺,老公的妹妹穿的比我還像新娘。我一直安慰自己贷岸,他們只是感情好壹士,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著偿警,像睡著了一般墓卦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上户敬,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機與錄音睁本,去河邊找鬼尿庐。 笑死,一個胖子當著我的面吹牛呢堰,可吹牛的內(nèi)容都是我干的抄瑟。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼枉疼,長吁一口氣:“原來是場噩夢啊……” “哼皮假!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起骂维,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤惹资,失蹤者是張志新(化名)和其女友劉穎缕允,沒想到半個月后婆誓,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體受啥,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡蹬屹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年强霎,在試婚紗的時候發(fā)現(xiàn)自己被綠了佣谐。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片规伐。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡做盅,死狀恐怖乖杠,靈堂內(nèi)的尸體忽然破棺而出分扎,到底是詐尸還是另有隱情,我是刑警寧澤胧洒,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布畏吓,位于F島的核電站墨状,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏庵佣。R本人自食惡果不足惜歉胶,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望巴粪。 院中可真熱鬧通今,春花似錦、人聲如沸肛根。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽派哲。三九已至臼氨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間芭届,已是汗流浹背储矩。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留褂乍,地道東北人持隧。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像逃片,于是被迫代替她去往敵國和親屡拨。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容