下面來(lái)通過(guò)一個(gè)實(shí)例講解Session認(rèn)證的方式
創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的青山網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
創(chuàng)建工程:
引入依賴:
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.4.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> </dependencies> <build> <finalName>security‐springmvc</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7‐maven‐plugin</artifactId> <version>2.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven‐compiler‐plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven‐resources‐plugin</artifactId> <configuration> <encoding>utf‐8</encoding> <useDefaultDelimiters>true</useDefaultDelimiters> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </configuration> </plugin> </plugins> </pluginManagement> </build>
Spring容器配置
在config包下定義ApplicationConfig.java,這個(gè)配置類相當(dāng)于spring的配置文件
@Configuration
@ComponentScan(basePackages = ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.)})ApplicationConfig { }
在config包下定義WebConfig.java,這個(gè)配置類相當(dāng)于springmv的配置文件
@Configuration @EnableWebMvc @ComponentScan(basePackages = "cn.xh" ,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})public class WebConfig implements WebMvcConfigurer { //視頻解析器 @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
加載spring容器
在init包下定義spring容器的初始化類SpringApplicationInitializer,該類實(shí)現(xiàn)了WebApplicationInitializer接口相當(dāng)于web.xml文件。Spring容器啟動(dòng)時(shí)會(huì)加載所有實(shí)現(xiàn)了WebApplicationInitializer接口的類。
public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { ApplicationConfig.class }; } @ Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebConfig.class }; } @ Override protected String[] getServletMappings() { return new String [] {"/"}; } }
該類對(duì)應(yīng)的web.xml文件可以參考:
<web‐app>
<listener>
<listener‐class>org.springframework.web.context.ContextLoaderListener</listener‐class>
</listener>
<context‐param>
<param‐name>contextConfigLocation</param‐name>
<param‐value>/WEB‐INF/application‐context.xml</param‐value>
</context‐param>
<servlet>
<servlet‐name>springmvc</servlet‐name>
<servletclass>org.springframework.web.servlet.DispatcherServlet</servlet‐class>
<init‐param>
<param‐name>contextConfigLocation</param‐name>
<param‐value>/WEB‐INF/spring‐mvc.xml</param‐value>
</init‐param>
<load‐on‐startup>1</load‐on‐startup>
</servlet>
<servlet‐mapping>
<servlet‐name>springmvc</servlet‐name>
<url‐pattern>/</url‐pattern>
</servlet‐mapping>
</web‐app>
實(shí)現(xiàn)認(rèn)證功能
在webapp/WEB-INF/views下定義認(rèn)證頁(yè)面login.jsp
<%@ pagecontentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>用戶登錄</title>
</head>
<body>
<formaction="login"method="post">
用戶名:<inputtype="text"name="username"><br>
密 碼:
<inputtype="password"name="password"><br>
<inputtype="submit"value="登錄">
</form>
</body>
</html>
在WebConfig中新增如下配置,將/直接導(dǎo)向login.jsp頁(yè)面:
@Override
public voidaddViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
}
啟動(dòng)項(xiàng)目,訪問(wèn)/路徑地址,進(jìn)行測(cè)試
創(chuàng)建認(rèn)證接口;
認(rèn)證接口用來(lái)對(duì)傳入的用戶名和密碼進(jìn)行驗(yàn)證,驗(yàn)證成功返回用戶的詳細(xì)信息,失敗拋出錯(cuò)誤異常。
public interfaceAuthenticationService {
/**
*用戶認(rèn)證
* @paramauthenticationRequest用戶認(rèn)證請(qǐng)求
* @return認(rèn)證成功的用戶信息
*/
UserDto authentication(AuthenticationRequest authenticationRequest);
}
認(rèn)證請(qǐng)求結(jié)構(gòu):
@Data
public classAuthenticationRequest {
/**
*用戶名
*/
privateString username;
/**
*密碼
*/
privateString password;
}
用戶詳細(xì)信息:
@Data
@AllArgsConstructor
public classUserDto {
privateString id;
privateString username;
privateString password;
privateString fullname;
privateString mobile;
}
認(rèn)證實(shí)現(xiàn)類:
@Service
public classAuthenticationServiceImpl implementsAuthenticationService {
@Override
publicUserDto authentication(AuthenticationRequest authenticationRequest) {
if(authenticationRequest == null
|| StringUtils.isEmpty(authenticationRequest.getUsername())
|| StringUtils.isEmpty(authenticationRequest.getPassword())){
throw newRuntimeException("賬號(hào)或密碼為空");
}
UserDto userDto = getUserDto(authenticationRequest.getUsername());
if(userDto == null){
throw newRuntimeException("查詢不到該用戶");
}
if(!authenticationRequest.getPassword().equals(userDto.getPassword())){
throw newRuntimeException("賬號(hào)或密碼錯(cuò)誤");
}
returnuserDto;
}
//模擬用戶查詢
publicUserDto getUserDto(String username){
returnuserMap.get(username);
}
//用戶信息
privateMap<String,UserDto> userMap= newHashMap<>();
{
userMap.put("zhangsan",newUserDto("1010","zhangsan","123","張三","133443"));
userMap.put("lisi",newUserDto("1011","lisi","456","李四","144553"));
}
}
登錄controller:
@RestController
public classLoginController {
@Autowired
privateAuthenticationService authenticationService;
/**
*用戶登錄
* @paramauthenticationRequest登錄請(qǐng)求
* @return
*/
@PostMapping(value = "/login",produces = "text/plain;charset=utf‐8")
publicString login(AuthenticationRequest authenticationRequest){
UserDto userDto = authenticationService.authentication(authenticationRequest);
returnuserDto.getFullname() + "登錄成功";
}
}
測(cè)試
實(shí)現(xiàn)會(huì)話功能:
當(dāng)用戶登錄系統(tǒng)后,系統(tǒng)需要記住用戶的信息,一般會(huì)把用戶的信息放在session中,在需要的時(shí)候從session中獲取用戶的信息,這就是會(huì)話機(jī)制。
首先在UserDto中定義一個(gè)Session_USER_KEY,作為session的key
public static finalString SESSION_USER_KEY= "_user";
修改LoginController,認(rèn)證成功后,將用戶的信息放入session,并增加用戶注銷(xiāo)的方法,用戶注銷(xiāo)時(shí)清空session
@PostMapping(value = "/login",produces = "text/plain;charset=utf‐8")
publicString login(AuthenticationRequest authenticationRequest, HttpSession session){
UserDto userDto = authenticationService.authentication(authenticationRequest);
//用戶信息存入session
session.setAttribute(UserDto.SESSION_USER_KEY,userDto);
returnuserDto.getUsername() + "登錄成功";
}
@GetMapping(value = "logout",produces = "text/plain;charset=utf‐8")
publicString logout(HttpSession session){
session.invalidate();
return"退出成功";
}
增加測(cè)試資源,在LoginController中增加測(cè)試資源:
@GetMapping(value = "/r/r1",produces = {"text/plain;charset=utf-8"})
publicString r1(HttpSession session){
String fullname = null;
Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
if(userObj != null){
fullname = ((UserDto)userObj).getFullname();
}else{
fullname = "匿名";
}
returnfullname + "訪問(wèn)資源1";
}
測(cè)試:
未登錄訪問(wèn) /r/r1顯示:
已登錄訪問(wèn) /r/r1顯示:
實(shí)現(xiàn)授權(quán)功能
用戶訪問(wèn)系統(tǒng)需要經(jīng)過(guò)授權(quán),需要完成如下功能:
禁止未登錄用戶訪問(wèn)某些資源
登錄用戶根據(jù)用戶的權(quán)限決定是否能訪問(wèn)某些資源
第一步:在UserDto里增加權(quán)限屬性表示該登錄用戶擁有的權(quán)限:
@Data
@AllArgsConstructor
public classUserDto {
public static finalString SESSION_USER_KEY= "_user";
privateString id;
privateString username;
privateString password;
privateString fullname;
privateString mobile;
/**
*用戶權(quán)限
*/
privateSet<String> authorities;
}
第二步:在AuthenticationServiceImpl中為用戶初始化權(quán)限,張三給了p1權(quán)限,李四給了p2權(quán)限:
//用戶信息
privateMap<String,UserDto> userMap= newHashMap<>();
{
Set<String> authorities1 = newHashSet<>();
authorities1.add("p1");
Set<String> authorities2 = newHashSet<>();
authorities2.add("p2");
userMap.put("zhangsan",newUserDto("1010","zhangsan","123","張三","133443",authorities1));
userMap.put("lisi",newUserDto("1011","lisi","456","李四","144553",authorities2));
}
第三步:在LoginController中增加測(cè)試資源:
/**
*測(cè)試資源2
* @paramsession
* @return
*/
@GetMapping(value = "/r/r2",produces = {"text/plain;charset=utf-8"})
publicString r2(HttpSession session){
String fullname = null;
Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
if(userObj != null){
fullname = ((UserDto)userObj).getFullname();
}else{
fullname = "匿名";
}
returnfullname + "訪問(wèn)資源2";
}
第四步:在interceptor包下實(shí)現(xiàn)授權(quán)攔截器SimpleAuthenticationInterceptor:
校驗(yàn)用戶是否登錄
校驗(yàn)用戶是否有操作權(quán)限
@Component
public classSimpleAuthenticationInterceptor implementsHandlerInterceptor {
//請(qǐng)求攔截方法
@Override
public booleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object
handler) throwsException {
//讀取會(huì)話信息
Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
if(object == null) {
writeContent(response, "請(qǐng)登錄");
}
UserDto user = (UserDto) object;
//請(qǐng)求的url
String requestURI = request.getRequestURI();
if(user.getAuthorities().contains("p1") && requestURI.contains("/r1")) {
return true;
}
if(user.getAuthorities().contains("p2") && requestURI.contains("/r2")) {
return true;
}
writeContent(response, "權(quán)限不足,拒絕訪問(wèn)");
return false;
}
//響應(yīng)輸出
private voidwriteContent(HttpServletResponse response, String msg) throwsIOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(msg);
writer.close();
response.resetBuffer();
}
}
在WebConfig中配置攔截器,配置/r/**的資源被攔截器處理:
@Autowired
privateSimpleAuthenticationInterceptor simpleAuthenticationInterceptor;
@Override
public voidaddInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/r/**");
}
測(cè)試:
未登錄:
張三訪問(wèn)/r/r1:
張三訪問(wèn) /r/r2:
分享名稱:通過(guò)session會(huì)話實(shí)現(xiàn)認(rèn)證和授權(quán)
轉(zhuǎn)載來(lái)源:http://jinyejixie.com/article20/iicjco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、網(wǎng)站內(nèi)鏈、網(wǎng)頁(yè)設(shè)計(jì)公司、定制網(wǎng)站、品牌網(wǎng)站建設(shè)、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)