[Spring Security] Authotization
Entity:
package com.frankmoley.security.app.auth; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="AUTH_USER_GROUP") public class AuthGroup { @Id @Column(name="AUTH_USER_GROUP_ID") @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name="USERNAME") private String username; @Column(name="AUTH_GROUP") private String authGroup; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAuthGroup() { return authGroup; } public void setAuthGroup(String authGroup) { this.authGroup = authGroup; } }
Repository:
package com.frankmoley.security.app.auth; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface AuthGroupRepository extends JpaRepository<AuthGroup, Long> { List<AuthGroup> findByUsername(String username); }
Config;
package com.frankmoley.security.app; import com.frankmoley.security.app.auth.LandonUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 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.core.authority.mapping.GrantedAuthoritiesMapper; import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; 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.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import java.util.ArrayList; import java.util.List; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{ @Autowired private LandonUserDetailsService userDetailsService; @Bean public DaoAuthenticationProvider authenticationProvider(){ DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService); provider.setPasswordEncoder(new BCryptPasswordEncoder(11)); provider.setAuthoritiesMapper(authoritiesMapper()); return provider; } @Bean public GrantedAuthoritiesMapper authoritiesMapper(){ SimpleAuthorityMapper authorityMapper = new SimpleAuthorityMapper(); authorityMapper.setConvertToUpperCase(true); authorityMapper.setDefaultAuthority("USER"); return authorityMapper; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/", "/index", "/css/*", "/js/*").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } }
Controller:
package com.frankmoley.security.app; import com.frankmoley.security.app.domain.Guest; import com.frankmoley.security.app.domain.GuestModel; import com.frankmoley.security.app.service.GuestService; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * @author Frank P. Moley III. */ @Controller @RequestMapping("/") public class GuestController { private final GuestService guestService; public GuestController(GuestService guestService){ super(); this.guestService = guestService; } @GetMapping(value={"/", "/index"}) public String getHomePage(Model model){ return "index"; } @GetMapping(value="/guests") @PreAuthorize("hasRole('ROLE_USER')") public String getGuests(Model model){ List<Guest> guests = this.guestService.getAllGuests(); model.addAttribute("guests", guests); return "guests-view"; } @GetMapping(value="/guests/add") @PreAuthorize("hasRole('ROLE_ADMIN')") public String getAddGuestForm(Model model){ return "guest-view"; } @PostMapping(value="/guests") @PreAuthorize("hasRole('ROLE_ADMIN')") public ModelAndView addGuest(HttpServletRequest request, Model model, @ModelAttribute GuestModel guestModel){ Guest guest = this.guestService.addGuest(guestModel); model.addAttribute("guest", guest); request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT); return new ModelAndView("redirect:/guests/" + guest.getId()); } @GetMapping(value="/guests/{id}") @PreAuthorize("hasRole('ROLE_USER')") public String getGuest(Model model, @PathVariable long id){ Guest guest = this.guestService.getGuest(id); model.addAttribute("guest", guest); return "guest-view"; } @PostMapping(value="/guests/{id}") @PreAuthorize("hasRole('ROLE_ADMIN')") public String updateGuest(Model model, @PathVariable long id, @ModelAttribute GuestModel guestModel){ Guest guest = this.guestService.updateGuest(id, guestModel); model.addAttribute("guest", guest); model.addAttribute("guestModel", new GuestModel()); return "guest-view"; } }
分类:
Java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-01-06 [Algorithm] Maximum Contiguous Subarray algorithm implementation using TypeScript / JavaScript
2016-01-06 [Javascript] Array methods in depth - some
2015-01-06 [MODx] 5. WayFinder
2015-01-06 [MODx] 4. getResources