AWS |
lambdaタグが付けられた新着投稿 - Qiita |
API Gateway、Cognito、Lambda、S3を使って署名付きアップロード・ダウンロードを実装する。 |
https://qiita.com/sakai00kou/items/ba5618f0a67064355752
|
apigateway |
2023-07-15 21:40:04 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
CSVファイルを開いてグラフ表示するGUIアプリを作ってみた! |
https://qiita.com/akiba_burari/items/0616793982411a985424
|
input |
2023-07-15 21:53:46 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
【AWS/ECS on EC2】 EC2コンテナインスタンスの登録方法 |
https://qiita.com/yokku21/items/1b7f51c4a0c1b1f64005
|
awsecsonec |
2023-07-15 21:43:25 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
API Gateway、Cognito、Lambda、S3を使って署名付きアップロード・ダウンロードを実装する。 |
https://qiita.com/sakai00kou/items/ba5618f0a67064355752
|
apigateway |
2023-07-15 21:40:04 |
技術ブログ |
Developers.IO |
[資料公開] Cloudflare Workersのユースケースと開発方法というタイトルで登壇しました #devio2023 |
https://dev.classmethod.jp/articles/devio2023-cloudflare-workers-usecase/
|
cloudflareworkers |
2023-07-15 12:30:48 |
海外TECH |
MakeUseOf |
The 4 Best Chrome Extensions to Find Memes |
https://www.makeuseof.com/meme-chrome-extensions/
|
google |
2023-07-15 12:30:20 |
海外TECH |
DEV Community |
Creating an Interactive Earth visualization with JavaScript and the Mapbox GL JS API |
https://dev.to/sarahokolo/creating-an-interactive-earth-visualization-with-javascript-and-the-mapbox-gl-js-api-4464
|
Creating an Interactive Earth visualization with JavaScript and the Mapbox GL JS API IntroductionEver wanted to travel the world wanted to get to see different locations in our planet Well sometimes our pocket and time doesn t grant us such luxury but don t worry just hitch a ride with me and let s go around the world from the comfort of your home I mean In this article I am going to walk you through how you can easily implement an interactive map into your project that would enable you view our beautiful planet from space down to the very building of your house or any other location of your choice Anyone with basic HTML CSS and JavaScript skills would be able to follow along So you yes you don t worry about not being well versed in any of the three it s as easy as pie to implement as the Mapbox GL JS API has been so very gracious to help with over of the complexity of this task Mapbox is a powerful vector based rendering engine capable of rendering dynamic maps in real time using WebGL It allows developers to create interactive customizable and visually stunning maps and geospatial applications Now that we know about Mapbox let s get started with our project shall we So buckle up as we re about to take off Table Of Contents TOC Setting Up the Html StructureAdding Styles to the PageRegistration and Obtaining Your Mapbox API CredentialsInitializing the Map in your JavaScript FileSetting Zooming and Panning ControlsConclusionSetting Up the Html StructureBefore we get started make sure you have created empty files which are the Html CSS and JavaScript files Now inside the Html file we are just going to create our basic standard Html boilerplate before anything else lt doctype html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta name viewport content width device width initial scale gt lt title gt View the Earth lt title gt lt head gt lt body gt lt body gt lt html gt Inside the body tag we include the header section of our project lt header gt lt h gt View the Earth lt h gt lt header gt Next let s create the container that is going to hold our map element as well as an extra div element that we are going to be styling later to create a shadow effect for more a D look of the planet lt div id map container gt lt div id map gt lt div gt lt div id shadow overlay gt lt div gt lt div gt After that we create a little button element that would be responsible later on for resetting the zoom and pan level of the map lt button id reset gt Reset Map lt button gt And that is basically all for our Html file Now lets add a few styles to really beautify our page Adding Styles to the PageHeading straight into our CSS file now let us add some overall basic styling to the page first of all margin padding box sizing border box Next we style the body of the page body display grid place items center min height vh max width vw background image url cs srgb amp fm jpg amp ixid MwzMjMNDZMHwxfHJhbmRvbXxfHxfHxfDEODkyNjINzl amp ixlib rb amp q background size cover background attachment fixed background position center After that lets go ahead to add styles to the rest sections of the page header padding top px text align center z index h text shadow px px px ff color aliceblue letter spacing px word spacing px margin bottom px map container position relative width max width px map width height border radius padding bottom box shadow px px px aa shadow overlay position absolute top left width height border radius box shadow inset px px px f pointer events none button margin top px font size px border radius px background color aa padding px color aliceblue box shadow px px px aa border none Okay we are done dressing up our Html document in a pretty outfit let s get to the most fun parts of the project Registration and Obtaining Your Mapbox API CredentialsTo be able to make use of the mapbox GL JS API in your project you are first required to have an account with them so you can obtain your access token This is a unique id that is given to every mapbox user which enables them have access to all the amazing features mapbox has to offer To create an account with them is super easy First head into their website and then click on the Start mapping for free buttonAfter you have created an account with them the next step you need to take is obtaining your access token You can do this by logging into you account which would take you to this page Scroll down to Access Tokens and copy the default access token provided there and just place it somewhere safe for now as we are going to be making use of it in our JavaScript file Initializing the Map in your JavaScript FileWhen you are done signing up and obtaining your access token on that same page go ahead and click on Install Mapbox GL JS which would then take you to this page Because we want to keep this project as simple as possible we would be making use of the Mapbox CDN and not the module bundler So click on the HTML image After that you should see yourself right on this page Copy the script and link tags you find there and place them inside the head tag in your Html file This would enable your document have access to the map styles and functionalities After you re done with that click on the Next button and it should take you to this page Now copy only the code that is imbetween the script tags head into your JavaScript file and paste it in there Replace YOUR MAPBOX ACCESS TOKEN with your actual access token which you copied earlier make sure it s still inside the double quotes There you have it the map has been initialized in your project as easy as pie Now we need to modify just a few things in the code For example we need to change the map view style to give us a more d aerial view of the planet for that we simply head into the mapbox styles page and select our desired style which in this case would be the Mapbox Satellite streets style you can find it by scrolling down on that page Copy the style code beside it and replace the the value of the style property present in your JavaScript file with it Setting Zooming and Panning ControlsNow that we are done Initializing the map in our project we need to add and modify the pan and zoom levels accordingly Inside the map object set the initial zoom level of the map and also its starting position center starting positionzoom The center property takes in an array of which is simply the longitude and latitude values in that order of the location you want to position to you can set any location you want simply just google the longitude and latitude values of the place and place them in the array like that Outside the map object we would need to set the minimum zoom level so the map cant be zoomed out more than the specified value in this case we use as our value map setMinZoom Next let us implement the functionality for our reset map button In the JavaScript file create a variable for the element to get its id const reset document getElementById reset After that we create an onclick event for the element which would enable us reset the initial values of the map s zoom level and position every time the button is clicked We want to use the transition animation effect to achieve this so we would be using the built in easeto mapbox function which takes in our map object reset onclick gt map easeTo zoom center duration The duration property is used to set the value of how long we want the transition to last in this case we set it to milliseconds seconds And there you have successfully created a live interactive visualization of earth Cheers to you ConclusionWell that s it for this article guys You can view the result and entire code of this project in the pen below set pen zoom level to x for better view The Mapbox API still has a whole lot of addons and features you can incorporate into your own map to make it more dynamic and interesting you can go to the Mapbox page to explore more of those features and all it has to offer Hopefully you have learned something new and can now also incorporate maps feature into any of your project Now go ahead and view the entirety of our beautiful planet earth explore the different locations you wish to visit If you have any questions please do not hesitate to ask them I respond promptly And as always Happy Coding |
2023-07-15 12:56:29 |
海外TECH |
DEV Community |
The Complete Guide to Becoming a Web Developer: Part 4 |
https://dev.to/aradwan20/the-complete-guide-to-becoming-a-web-developer-part-4-3oj9
|
The Complete Guide to Becoming a Web Developer Part Welcome fellow web explorers Today we continue with our becoming a web developer series and embark on an exciting journey into the heart of modern web development Our travel companions Three powerful technologies have revolutionized how we interact with the web AJAX JSON and APIs If you are new here you can start with part part or part Now let s start with a quick introduction IntroductionSection Deep Look into AJAX JSON and APIsWhat is AJAX Making XMLHttpRequests XHR XMLHttpRequest XHR FetchAxiosSection Deep Look into JSONWhat is JSON Basic Rules for Writing JSONData Types in JSONWhat is a JSON Schema Why is JSON Schema Useful Validating JSON Data Against a SchemaCommon Security ConcernsCross Site Scripting XSS Insecure DeserializationBest Practices to Mitigate JSON Security RisksValidate and Sanitize InputUse HTTPOnly CookiesSecure Your Deserialization ProcessUse Content Security Policy CSP Section Deep Look into APIWhat are APIs HTTP VerbsGETPOSTPUTDELETEPATCHHTTP Status Codesxx Successxx Redirectionxx Client errorsxx Server errorsQuery StringsHTTP HeadersSecurity ConsiderationsCORSCSRFConclusionAdditional ResourcesIntroductionAJAX Asynchronous JavaScript and XML is like a secret agent for your web page It works behind the scenes communicating with the server fetching data and updating the web page all without needing to reload the entire page This makes for a smooth seamless user experience Imagine being able to update a news feed post a comment or load more items in a shopping category without a page refresh That s AJAX in action Next up we have JSON JavaScript Object Notation JSON is the language of data on the web It s a simple lightweight format for storing and transporting data JSON is easy for humans to read and write and easy for machines to parse and generate It s like the universal translator for data on the web allowing different systems and programming languages to communicate and exchange data with ease Last but not least we have APIs Application Programming Interfaces An API is like a menu in a restaurant It provides a list of operations that are available for you to use When you interact with an API you re telling it what operation you want to perform and the API takes care of the rest APIs are used everywhere in web development from fetching data from a database to interacting with external services like social media platforms weather services payment gateways and many other examples Together AJAX JSON and APIs form the backbone of dynamic interactive web applications They allow us to create rich responsive user experiences and open up a world of possibilities for what we can achieve with our web applications So buckle up and get ready for an adventure By the end of this journey you ll have a solid understanding of AJAX JSON and APIs and you ll be equipped with the knowledge and skills to use them effectively in your own projects Let s dive in Section Deep Look into AJAXIn this section we re going to dive deeper into AJAX JSON and APIs These three technologies are the pillars of modern web development enabling us to create dynamic interactive web applications Let s break them down one by one What is AJAX AJAX stands for Asynchronous JavaScript and XML It s a technique that allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes This means that it is possible to update parts of a web page without reloading the whole page Let s break it down Asynchronous This means that AJAX allows you to send and receive data in the form of HTTP requests to a server in the background without interfering with the display and behavior of the existing page JavaScript AJAX is implemented using JavaScript JavaScript has the ability to send a request to a server and to react to the response XML This stands for eXtensible Markup Language Despite its name AJAX doesn t require the use of XML AJAX applications can send data as plain text or as JSON text Here s a simple example of an AJAX request using the Fetch API fetch method GET then response gt response json then data gt console log data catch error gt console error Error error In this example we re sending a GET request to When we receive the response we convert it to JSON and log it to the console Making XMLHttpRequests XHR XMLHttpRequest XHR objects are like the Swiss Army knives of AJAX They re used to interacting with servers and can retrieve data from a URL without having to do a full page refresh This makes them a powerful tool for creating dynamic interactive web applications Here s how you might create and send an XMLHttpRequest var xhr new XMLHttpRequest create a new XMLHttpRequest objectxhr open GET true specify the type of request the URL and whether the request should be asynchronousxhr onreadystatechange function set up a function to run when the state of the request changes if xhr readyState amp amp xhr status check if the request has been completed successfully console log JSON parse xhr responseText log the response data to the console xhr send send the requestIn this example we re sending a GET request to When the request is complete and successful we log the response data to the console When I say that XMLHttpRequests are used to interact with servers and can retrieve data from a URL without having to do a full page refresh I m referring to the ability to send HTTP requests directly from JavaScript running in the browser This allows you to fetch data from a server and update the content of your web page without having to reload the entire page This is a fundamental aspect of AJAX Asynchronous JavaScript and XML which is a set of web development techniques used to create asynchronous web applications With AJAX you can send and receive data from a server after the page has loaded and update parts of a web page without reloading the whole page Here s a simple example let s say you have a web page that displays a list of users Without AJAX if you wanted to add a new user to the list you would have to submit a form the server would have to process the request and generate a new HTML page and then the entire page would have to be reloaded in the browser to display the updated list With AJAX you can send a request to the server to add a new user and then just update the part of the page that displays the list of users with the new user The rest of the page doesn t need to be reloaded Here s what that might look like with an XMLHttpRequest var xhr new XMLHttpRequest xhr open POST true xhr setRequestHeader Content Type application json xhr onreadystatechange function if xhr readyState amp amp xhr status var newUser JSON parse xhr responseText var userList document getElementById userList var newUserElement document createElement li newUserElement textContent newUser name userList appendChild newUserElement xhr send JSON stringify name John Doe email john example com In this example we re sending a POST request to to add a new user When we receive the response from the server we create a new list item with the new user s name and append it to the user list The rest of the page doesn t need to be reloaded This ability to update parts of a web page without reloading the whole page is a key aspect of many modern web development frameworks and libraries such as React Angular and Vue js These frameworks and libraries provide more advanced and efficient ways to update the DOM based on changes in application state but the fundamental concept of updating parts of a web page without reloading the whole page is the same While XMLHttpRequests are powerful they can be a bit verbose and complex to set up especially for more complex requests This has led to the development of newer APIs like the Fetch API and libraries like Axios which provide a more modern and powerful interface for making HTTP requests Let s have a comparison between all three so we can appreciate the amount of work done on these new tools first start with XMLHttpRequest XMLHttpRequest XHR XMLHttpRequest is the original method for making AJAX requests It s supported in all browsers and has a wide range of features However its API is a bit clunky and outdated compared to newer methods For example var xhr new XMLHttpRequest xhr open GET xhr onreadystatechange function if xhr readyState amp amp xhr status console log JSON parse xhr responseText xhr send As you can see the XHR API involves a lot of boilerplate code and manual handling of the response FetchThe Fetch API is a modern alternative to XHR that provides a more powerful and flexible feature set It s built into most modern browsers and returns Promises which are easier to work with than the callbacks used by XHR Here s how you might make a GET request with the Fetch API fetch then response gt response json then data gt console log data catch error gt console error Error error As you can see the Fetch API is much cleaner and easier to use than XHR However it s not supported in Internet Explorer and it doesn t automatically send or receive cookies AxiosAxios is a promise based HTTP client that works in the browser and in Node js It has a simple API and provides several features that aren t available in the Fetch API such as automatic transformation of JSON data and progress events Here s how you might make a GET request with Axios axios get then response gt console log response data catch error gt console error Error error Section Deep Look into JSONWhat is JSON JSON or JavaScript Object Notation is a lightweight data interchange format It s a way of encoding data structures that ensures that they are easy for humans to read and write and easy for machines to parse and generate It s primarily used to transmit data between a server and a web application serving as an alternative to XML Here s an example of what JSON data might look like name John Doe email john example com age isMember true In this example we have a JSON object that represents a user It has four properties name email age and isMember Basic Rules for Writing JSONJSON syntax is derived from JavaScript object notation syntax but the JSON format is text only Code for reading and generating JSON data can be written in any programming language Here are the basic rules for writing JSON Data is in name value pairs JSON data is written as name value pairs just like JavaScript object properties A name value pair consists of a field name in double quotes followed by a colon followed by a value like so name John Data is separated by commas Just like in JavaScript we can write multiple name value pairs in JSON and they must be separated by commas For example name John age city New York Curly braces hold objects In JSON curly braces hold objects and each name is followed by a colon The name value pairs are separated by a comma For example name John age city New York Square brackets hold arrays In JSON square brackets hold arrays For example employees John Anna Peter Data Types in JSONJSON supports various data types including Numbers No difference between integer and float Also no restrictions on number size For example age or average Strings A collection of characters enclosed in double quotes For example name John Boolean True or false For example sale true Array An ordered list of or more values For example employees John Anna Peter Object An unordered collection of key value pairs i e a string value pair For example employee name John age city New York null An empty value For example middlename null Here s an example of a JSON object that includes all these data types JSON Schema is a powerful tool for validating the structure of JSON data It describes your existing data format in a clear human and machine readable way With JSON Schema you can ensure the data you re receiving or sending follows a specific structure with defined data types value formats and even complex constraints What is a JSON Schema A JSON Schema is a JSON object that defines various attributes of the data including properties required properties default values and data types It provides a contract for the JSON data required by a given application and how that data can be modified For example let s say we have a JSON object for a person name John age city New York A simple JSON Schema for this object could look like this type object properties name type string age type number city type string required name age In this schema we define that our data is an object type object with properties name age and city The name and city are of type string and age is of type number We also specify that name and age are required properties Why is JSON Schema Useful JSON Schema is particularly useful in the following scenarios Validation You can validate that the JSON sent to your application by a client meets the expectations and won t break your code Automated Testing You can generate mock data for your tests based on your schema Documentation Your schema serves as a form of documentation for your API It s a single source of truth that describes the shape of your data IDE Support Some IDEs can validate JSON data on the fly using JSON Schema which can be a big help during development Validating JSON Data Against a SchemaThere are many libraries available that can validate JSON data against a JSON Schema One popular option for JavaScript is ajv Here s an example of how you might use ajv to validate data against a schema const Ajv require ajv const ajv new Ajv const schema type object properties name type string age type number city type string required name age const validate ajv compile schema const data name John age const valid validate data if valid console log Data is valid else console log Data is invalid validate errors In this example we first compile our schema into a validation function using ajv compile We then validate our data using this function If the data is valid we print a success message If it s not we print the validation errors Common Security ConcernsCross Site Scripting XSS Cross Site Scripting XSS is a type of security vulnerability typically found in web applications XSS attacks enable attackers to inject client side scripts into web pages viewed by other users If an attacker can inject malicious scripts into a JSON response that is then executed in the browser they can potentially steal sensitive data perform actions on behalf of the user or carry out other harmful actions Insecure DeserializationInsecure deserialization is another common security concern when working with JSON Deserialization is the process of converting a serialized format like a JSON string back into a JavaScript object If an attacker can manipulate the serialized data and the application doesn t properly validate or sanitize the deserialized data it can lead to various types of attacks including code injection privilege escalation or Denial of Service DoS Best Practices to Mitigate JSON Security RisksValidate and Sanitize InputAlways validate and sanitize input data whether it s coming from a user form or a JSON payload This can help prevent XSS attacks and other types of input based attacks There are many libraries available that can help with this such as validator js for Node js Use HTTPOnly CookiesTo help prevent XSS attacks consider storing sensitive data in HTTPOnly cookies These cookies cannot be accessed by JavaScript which means they can t be stolen by an XSS attack Secure Your Deserialization ProcessTo mitigate the risks associated with insecure deserialization be sure to validate and sanitize your serialized data before deserializing it Also consider using safe serialization and deserialization libraries that have built in protections against these types of attacks Use Content Security Policy CSP Content Security Policy CSP is a security layer that helps detect and mitigate certain types of attacks including XSS and data injection attacks By defining the sources from which the browser is allowed to load resources CSP can significantly reduce the risk and impact of XSS attacks Section Deep Look into APIWhat are APIs APIs or Application Programming Interfaces are sets of rules that allow different software applications to communicate with each other They define the methods and data formats that a program can use to communicate with other programs In the context of web development APIs often refer to web services that return data This data can be used to update a web page with new information without needing to refresh the page Here s an example of how you might use an API fetch then response gt response json then data gt console log data In this example we re sending a request to which is an API that returns a list of users We then log the data to the console HTTP VerbsAs you can see in the above we did a lot of requests using this protocol called HTTP Let s now dig deep into that and what other types of requests verbs or methods include with that HTTP verbs also known as methods are the actions that we can perform on resources They form the backbone of any HTTP request and understanding them is crucial to working with APIs Let s dive into the most common ones GET POST PUT DELETE and PATCH GETThe GET method is used to retrieve data from a server It s like saying Hey server can you give me the information located at this specific URL Here s an example of a GET request using the Fetch API fetch then response gt response json then data gt console log data In this example we re asking the server to give us the list of users The server then responds with the data which we log to the console POSTThe POST method is used to send data to the server This could be anything from submitting a form to adding a new item in a database Here s an example of a POST request fetch method POST headers Content Type application json body JSON stringify name John Doe email john example com then response gt response json then data gt console log data In this example we re sending a new user to the server to be added to the database The server then responds with the data of the newly created user PUTThe PUT method is used to update a resource on the server It s like saying Hey server can you update the information at this specific URL with this new data Here s an example of a PUT request fetch method PUT headers Content Type application json body JSON stringify name John Doe email john example com then response gt response json then data gt console log data In this example we re updating the user with the ID of The server then responds with the data of the updated user DELETEThe DELETE method is used to remove a resource from the server It s like saying Hey server can you delete the information at this specific URL Here s an example of a DELETE request fetch method DELETE then response gt response json then data gt console log data In this example we re deleting the user with the ID of The server then responds with a confirmation of the deletion PATCHThe PATCH method is used to partially update a resource on the server Unlike PUT which updates the entire resource PATCH only updates the fields that were included in the request Here s an example of a PATCH request fetch method PATCH headers Content Type application json body JSON stringify email john example com then response gt response json then data gt console log data In this example we re only updating the email of the user with the ID of The server then responds with the data of the updated user These are the most common HTTP verbs you ll encounter when working with APIs As you continue your journey into web development you ll find these methods to be your trusty tools helping you interact with the vast world of data on the web Happy journey HTTP Status CodesHTTP status codes are like the server s way of communicating with us They re three digit numbers that tell us whether our HTTP request was successful and if not what went wrong Understanding these status codes is crucial for debugging and handling errors in our applications Let s dive into the four main categories of HTTP status codes xx xx xx and xx xx Successxx status codes mean that our request was successful The most common xx status code you ll encounter is which means OK This status code is returned when our GET or POST request was successfully received understood and accepted Here s an example of how you might handle a successful response fetch then response gt if response status return response json else throw new Error Something went wrong on api server then data gt console log data catch error gt console error error In this example we re checking if the status code is If it is we proceed with our code If it s not we throw an error xx Redirectionxx status codes mean that the client must take additional action to complete the request This is often used for URL redirection For example a status code means Moved Permanently indicating that the resource has been permanently moved to a new URL and the client should proceed to that URL xx Client errorsxx status codes mean that there was a problem with the request This is often due to something the client did like requesting a resource that doesn t exist or not providing a valid authentication token The most common xx status code is which means Not Found This status code is returned when the server can t find the requested resource xx Server errorsxx status codes mean that the server failed to fulfill a valid request The most common xx status code is which means Internal Server Error This status code is returned when the server encountered an unexpected condition that prevented it from fulfilling the request Understanding HTTP status codes is crucial for handling responses and errors in our applications By checking the status code of a response we can determine whether our request was successful and if not what went wrong This allows us to handle errors gracefully and provide a better user experience So next time you see a status code don t be scared it s just the server s way of talking to you Query StringsQuery strings are like the secret messages of the web They re part of a URL that contains data to be passed to web applications They re often used to send data from a client to a server and they can be incredibly useful for things like tracking user activity storing user preferences and more A query string starts with a question mark and is followed by a series of parameters Each parameter is a key value pair and multiple parameters are separated by an ampersand amp Here s what a query string might look like param valueIn this example the query string is param value amp param value It contains two parameters param with a value of value and param with a value of value Query strings are often used in GET requests to send data to the server For example if you re building a search feature for your website you might use a query string to send the user s search term to the server Here s what that might look like let searchTerm javascript fetch searchTerm then response gt response json then data gt console log data In this example we re sending a GET request to The server would then return the search results for javascript To sum it up query strings are a powerful tool in web development They allow us to send data from the client to the server in a simple and efficient way So next time you see a question mark in a URL remember it s not just a punctuation mark it s a query string HTTP HeadersHTTP headers are like the secret whispers of an HTTP request or response They allow the client and the server to pass additional information along with the request or response They re not typically visible to the user but they play a crucial role in the HTTP communication process HTTP headers are defined by their name and value and they re structured like this Header Name Header Value There are many different types of HTTP headers but here are a few of the most common ones you ll encounter Content Type This header tells the server what type of data is being sent For example Content Type application json indicates that the data is in JSON format Authorization This header is used to authenticate a user For example Authorization Bearer your token would include a bearer token for authentication Look for further details on OAuth User Agent This header provides information about the client like the browser and operating system Accept This header tells the server what media types the client will accept Here s an example of how you might set headers in a fetch request fetch method POST headers Content Type application json Authorization Bearer your token body JSON stringify name John Doe email john example com then response gt response json then data gt console log data In this example we re sending a POST request to We re including two headers Content Type and Authorization The Content Type header tells the server that we re sending JSON data and the Authorization header includes our bearer token for authentication HTTP headers are a powerful tool in web development They allow us to send additional information with our HTTP requests and responses enabling us to do things like authenticate users specify the type of data we re sending and much more So next time you re sending an HTTP request don t forget about headers they might just be the secret ingredient you need Security ConsiderationsIn the realm of AJAX JSON and APIs security is like the castle walls that protect your kingdom It s crucial to understand and implement security measures to protect your data and your users Two important security considerations when working with APIs are Cross Origin Resource Sharing CORS and Cross Site Request Forgery CSRF CORSCross Origin Resource Sharing CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin access to selected resources from a different origin By default web browsers prohibit AJAX requests to different domains for security reasons However APIs can use CORS to allow other domains to make AJAX requests to them Here s an example of how you might set the CORS headers in an Express js server app use req res next gt res header Access Control Allow Origin res header Access Control Allow Headers Origin X Requested With Content Type Accept next In this example we re using Express js middleware to set the CORS headers for every response We re allowing access from and allowing the Origin X Requested With Content Type and Accept headers in requests Remember to replace with the actual origin you want to allow or a variable that contains the origin If you need to allow multiple specific origins you ll need to check the Origin header of each request and set the Access Control Allow Origin header accordingly CSRFCross Site Request Forgery CSRF is an attack that tricks the victim into submitting a malicious request It uses the identity and privileges of the victim to perform an undesired function on their behalf To protect against CSRF attacks you can use a CSRF token A CSRF token is a unique random value associated with a user s session This token is included as a parameter in unsafe methods such as POST and DELETE and the server checks this token before processing the request If the token is missing or incorrect the server rejects the request Here s an example of how you might include a CSRF token in an AJAX request axios method post url data name John Doe email john example com headers X CSRF Token your csrf token then response gt console log response data catch error gt console error Error error In this example we re including the CSRF token in the X CSRF Token header ConclusionWe ve come a long way in this guide diving deep into the world of AJAX JSON and APIs We ve explored the fundamental concepts compared different methods for making HTTP requests and even built a simple web application using these technologies We started by understanding AJAX JSON and APIs and how they work together to create dynamic and interactive web applications We then dived into the details of HTTP verbs status codes headers and query strings We learned how to make XMLHttpRequests XHR and how to use the Fetch API and Axios for making HTTP requests We also discussed setting headers with Axios and the importance of error handling and security considerations when working with APIs Remember the key to mastering these concepts is practice Don t be afraid to experiment with different APIs try out different HTTP methods and build your own projects The more you practice the more comfortable you ll become with these technologies Additional ResourcesFor further reading and learning here are some recommended online resources MDN Web Docs A comprehensive resource for developers with detailed documentation on JavaScript AJAX JSON APIs and much more JSONPlaceholder A free online REST API that you can use for testing and prototyping HTTP Status Codes A handy reference for HTTP status codes Axios GitHub Repository The official GitHub repository for Axios with detailed documentation and usage examples Fetch API Introduction on JavaScript info A detailed guide on the Fetch API Remember the journey of learning never ends Keep exploring keep building and most importantly have fun along the way Happy coding |
2023-07-15 12:54:19 |
海外TECH |
DEV Community |
Authentication for Spring Boot App with Authgear and OAuth2 |
https://dev.to/bobur/authentication-for-spring-boot-app-with-authgear-and-oauth2-48hb
|
Authentication for Spring Boot App with Authgear and OAuthAuthgear is a free to use identity platform to manage access to your applications It uses a special OpenID Connect OIDC protocol and OAuth Authorization Framework to confirm who users are and allow disallows them access to protected resources With Authgear you can easily add different ways for users to log in and access your apps and APIs without needing to worry about the technical details of how it all works Authgear takes care of the complicated parts of verifying users and granting them permission so you can focus on building your applications and business value features In this post you will learn how to add authentication to your Java Spring Boot application using OAuth with Authgear as the Identity Provider IdP Learning objectivesYou will learn the following throughout the article How Authorization code flow works How to create an app on Authgear How to enable Email based login Add sign up and login features to Spring Boot App How Authorization Code Flow works with AuthgearBefore diving into implementation let s understand first the Authorization Code Flow works in our example This flow can only be used for confidential applications such as Regular Web Applications because involves exchanging an authorization code for a token Here are steps in this flow User selects Login within the Spring application Spring Security redirects the user to Authgear Authorization Server oauth authorize endpoint Authgear redirects the user to the login page and authorization prompt The user authenticates using one of the configured login options for example by Email Authgear redirects the user back to the application with a single use authorization code Spring OAuth client sends the authorization code application s client ID and application s credentials such as a client secret to Authgear oauth token endpoint Authgear verifies the authorization code the application s client ID and the application s credentials Authgear responds with an ID token and access token and optionally a refresh token The application can use the access token to call an API to access information about the user API responds with requested data Add login to your Spring WebappThis example uses Spring MVC with Thymeleaf and SpringSecurity to build a regular web application and it uses Authgear to add authentication with the login page provided by Authgear The full source code of the examples can be found on GitHub PrerequisitesBefore you get started you will need the following Java or higher You can use SDKMAN to install Java if you don t have it already A free Authgear account Sign up if you don t have one already Part Configure AuthgearTo use Authgear services you ll need to have an application set up in the Authgear Dashboard The Authgear application is where you will configure how you want authentication to work for the project you are developing Step Configure an applicationUse the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with Every application in Authgear is assigned an alphanumeric unique client ID that your application code will use to call Authgear APIs through the Spring Boot OAuth Client Note down the Authgear issuer for example CLIENT ID CLIENT SECRET and OpenID endpoints from the output You will use these values in the next step for the client app config Step Configure Redirect URIA Redirect URI is a URL in your application that you would like Authgear to redirect users to after they have authenticated In our case it will be a home page for our Spring Boot App If not set users will not be returned to your application after they log in Step Choose a Login methodAfter you created the Authgear app you choose how users need to authenticate on the login page From the “Authentication tab navigate to “Login Methods you can choose a login method from various options including by email mobile or social just using a username or the custom method you specify For this demo we choose the Email Passwordless approach where our users are asked to register an account and log in by using their emails They will receive a One time password OTP to their emails and verify the code to use the app Part Configure Spring Boot application Step Add Spring dependenciesTo create a new Spring Boot application you use the Spring Initializr Then you add dependencies to pom xml file such as spring boot starter oauth client starter provides all the Spring Security dependencies needed to add authentication to your web application and Thymeleaf is used just to build a single page UI lt dependencies gt lt dependency gt lt groupId gt org springframework boot lt groupId gt lt artifactId gt spring boot starter web lt artifactId gt lt dependency gt lt dependency gt lt groupId gt org springframework boot lt groupId gt lt artifactId gt spring boot starter oauth client lt artifactId gt lt dependency gt lt dependency gt lt groupId gt org springframework boot lt groupId gt lt artifactId gt spring boot starter thymeleaf lt artifactId gt lt dependency gt lt dependency gt lt groupId gt org thymeleaf extras lt groupId gt lt artifactId gt thymeleaf extras springsecurity lt artifactId gt lt version gt RELEASE lt version gt lt dependency gt lt dependencies gt Step Configure OIDC authentication with AuthgearSpring Security makes it easy to configure your application for authentication with OIDC providers such as Authgear We need to add the client credentials to the application properties file with your Auhgear provider configuration You can use the sample below and replace properties with the values from your Authgear app spring security oauth client registration authgear client id your client id spring security oauth client registration authgear client secret your client secret spring security oauth client registration authgear authorization grant type authorization codespring security oauth client registration authgear scope openidspring security oauth client registration authgear redirect uri http localhost spring security oauth client provider authgear token uri https DOMAIN oauth tokenspring security oauth client provider authgear authorization uri https DOMAIN oauth authorize To logout from the appauthgear oauth end session endpoint https DOMAIN oauth end session Step Add login to your applicationTo enable user login with Authgear create a class that will provide an instance of SecurityFilterChain add the EnableMethodSecurity annotation and override the necessary method Configuration EnableMethodSecurity securedEnabled true public class SecurityConfig Value authgear oauth end session endpoint private String endSessionEndpoint Bean public SecurityFilterChain configure HttpSecurity http throws Exception http authorizeHttpRequests requests gt requests allow anonymous access to the root page requestMatchers permitAll authenticate all other requests anyRequest authenticated enable OAuth OIDC oauthLogin withDefaults configure logout handler logout logout gt logout logoutRequestMatcher new AntPathRequestMatcher logout logoutSuccessUrl addLogoutHandler oidcLogoutHandler return http build LogoutHandler oidcLogoutHandler return request response authentication gt try response sendRedirect endSessionEndpoint catch IOException e throw new RuntimeException e Step Add front pageWe create a simple home html page using Thymeleaf templates When a user opens the page running on http localhost we show the page with buttons for login or logout Step Add controllerNext we create a controller class to handle the incoming request This controller renders the home html page When the user authenticates the application retrieves the user s profile information attributes to render the page Controllerpublic class HomeController GetMapping String home return home Step Run the ApplicationTo run the application you can execute the mvn spring boot run goal Or run from your editor the main ExampleApplication java file The sample application will be available at http localhost Click on the Login button to be redirected to the Authgear login page You can also customize the login page UI view from the Authgear Portal After you sign up you will receive an OTP code in your email to verify your identity And log into your new account you will be redirected back to the home page You have successfully configured a Spring Boot application to use Authgear for authentication Now users can sign up for a new account log in and log out Next stepsThere is so much more you can do with Authgear Explore other means of login methods such as using Magic links in an email social logins or WhatsApp OTP For the current application you can also add more users from the Authgear portal Related resourcesAuthentication as a Service What Is It and Why You Need ItFrictionless Authentication What Is It amp How To Implement It Recommended contentSocial Login Why You Should Implement ItWeb Application Authentication How It Works and How to Implement It Community Join the Authgear Community on Discord Follow on Twitter Ask questions Check out open source SDKs About the authorVisit my blog www iambobur com |
2023-07-15 12:13:09 |
海外TECH |
Engadget |
Appeals court pauses order that restricts Biden officials from contacting social networks |
https://www.engadget.com/appeals-court-pauses-order-that-restricts-biden-officials-from-contacting-social-networks-123040377.html?src=rss
|
Appeals court pauses order that restricts Biden officials from contacting social networksBiden administration officials can freely communicate with social media companies ーfor now The th Circuit Court of Appeals has put a pause on Judge Terry A Doughty s order that prohibits most federal officials from talking to companies like Meta about content According to The New York Times the three judge panel has ruled for Doughty s preliminary injunction to be put aside quot until further orders of the court quot If you ll recall the state attorneys general of Louisiana and Missouri filed a lawsuit against President Joe Biden and other top government officials including Dr Anthony Fauci They accused the current administration of pressuring social media companies to censor certain topics and remove content The lawsuit the Washington Post reports is based on emails between the administration and social networks wherein the former questioned the companies handling of posts on their websites containing conservative claims on the COVID pandemic and the presidential elections as well as anti vaccine sentiments nbsp Doughty a Trump appointed judge said the plaintiffs quot produced evidence of a massive effort quot by the defendants quot to suppress speech based on its content quot He also wrote in his decision that if the allegations are true quot the present case arguably involves the most massive attack against free speech in United States history quot His order prohibits federal agencies that include the Department of Health and Human Services and the Department of Homeland Security from asking online platforms to take down content with quot protected free speech quot They could still however communicate with those entities for issues related to criminal activity national security and election interference by foreign players nbsp Conservatives have long believed that mainstream social media platforms are biased against right wing ideologies That had led to the launch of social networks associated with conservatives such as Parler and Donald Trump s Truth Social The state attorneys argued that federal officials crossed the line by threatening to take antitrust actions against social networks and to limit their Section protections which allow internet companies to moderate content on their platforms as they see fit It s worth noting that former President Trump previously signed an executive order that sought to limit federal protections offered by Section after Twitter fact checked a false tweet he posted The Justice Department appealed Doughty s order the day after it was issued arguing that it was too broad and could limit the government s ability to warn people about false information in times of emergency Apparently the administration has already felt its effects after its scheduled meeting with Meta to discuss strategies on how to counter foreign disinformation campaigns was cancelled This stay will allow federal agencies to continue working with online platforms until the court could look further into the complaint The appeals court has ordered for the case s oral arguments to be expedited so a final decision could be reached in the near future nbsp This article originally appeared on Engadget at |
2023-07-15 12:30:40 |
ニュース |
BBC News - Home |
Lucy Spraggan: Former X Factor star reveals sexual assault during filming |
https://www.bbc.co.uk/news/entertainment-arts-66210009?at_medium=RSS&at_campaign=KARANGA
|
hotel |
2023-07-15 12:03:33 |
ニュース |
BBC News - Home |
Declan Rice: Arsenal sign England midfielder from West Ham for £105m |
https://www.bbc.co.uk/sport/football/65982835?at_medium=RSS&at_campaign=KARANGA
|
worth |
2023-07-15 12:39:05 |
ニュース |
BBC News - Home |
Wimbledon 2023: GB's Alfie Hewett wins against Martin de la Puente - best shots |
https://www.bbc.co.uk/sport/av/tennis/66211254?at_medium=RSS&at_campaign=KARANGA
|
Wimbledon GB x s Alfie Hewett wins against Martin de la Puente best shotsWatch the best shots as Great Britain s Alfie Hewett beats Martin de la Puente in straight sets to progress to the men s wheelchair final at Wimbledon |
2023-07-15 12:37:43 |
ニュース |
BBC News - Home |
Wimbledon 2023: GB's Henry Searle beats Cooper Williams in juniors - best shots |
https://www.bbc.co.uk/sport/av/tennis/66211253?at_medium=RSS&at_campaign=KARANGA
|
wimbledon |
2023-07-15 12:43:51 |
コメント
コメントを投稿